The entrapment of bacteria near boundary surfaces is of biological and practical importance, yet the underlying physics is not well understood. We demonstrate that it is crucial to include a commonly neglected thermodynamic effect related to the spatial variation of hydrodynamic interactions, through a model that provides analytic explanation of bacterial entrapment in two dimensionless parameters: α_{1} the ratio of thermal energy to self-propulsion, and α_{2} an intrinsic shape factor. For α_{1} and α_{2} that match an Escherichia coli at room temperature, our model quantitatively reproduces existing experimental observations, including two key features that have not been previously resolved: The bacterial "nose-down" configuration, and the anticorrelation between the pitch angle and the wobbling angle. Furthermore, our model analytically predicts the existence of an entrapment zone in the parameter space defined by {α_{1},α_{2}}.