官术网_书友最值得收藏!

Container security layering with limited users

The following novel block of code in our Dockerfile is probably a little bit of a convoluted puzzle, but we will go through it together:

RUN mkdir -p $SRV_PATH && \
groupadd -r -g 350 pythonsrv && \
useradd -r -m -u 350 -g 350 pythonsrv

This is something we need to expand on multiple levels, but the first thing you need to know is that by default, Dockerfile directives are executed as root, and if at any point later you do not specify a different USER, your service will run with root credentials, which is a massive hole from a security perspective that we are trying to patch up by running our service as a limited user only. However, without the user and group defined, we cannot switch our context away from the root, so we create both a pythonsrv group first and then we follow it up by creating the pythonsrv user attached to the said group. The -r flags mark the user and group a system-level entity and is a good practice for groups and users that will not be directly logged into.

Speaking of users and groups, if you mount a volume from the host to the Docker container that is running as a limited user, if neither the host nor the container perfectly agree on the user and group IDs (uid and gid, respectively), you cannot read or write files from volumes. To avoid this situation, we use a stable UID and GID of 350 that is easy to remember and is not normally in the regular UID/GID tables on most host systems. This number is mostly arbitrary, but as long as it is in the service range for your host OS and doesn't clash with the users or groups on the host either, it should be fine.

The last flag that wasn't covered so far is -m, and what it does is create the home directory skeleton files for the user. Most of the time, you will not need this, but if any subsequent operations try to use $HOME (such as npm or a large swathe of other services), there will be no such directory unless you specify this flag and your build will fail so we make sure we do not hit this condition by creating $HOME for the pythonsrv user.

To round this off, we chained all of these RUN commands together to ensure that we use as few layers as we can. Each layer creates additional metadata and increases the size of your image, so just like the Docker best practices document states, we try to reduce them by stacking these commands together. While it is not the best thing to do in all cases as debugging this style of configuration is pretty difficult, it does usually trim the container size significantly.

主站蜘蛛池模板: 阿拉善盟| 丹寨县| 长丰县| 定远县| 泰和县| 茶陵县| 漳平市| 延吉市| 临漳县| 花莲县| 武强县| 康乐县| 大余县| 昭觉县| 清苑县| 莱州市| 宽甸| 进贤县| 桓仁| 平陆县| 岳阳市| 韩城市| 江西省| 含山县| 阆中市| 萝北县| 高平市| 巢湖市| 乌拉特后旗| 富源县| 罗甸县| 灵川县| 蓬溪县| 仁怀市| 田东县| 五莲县| 营山县| 建阳市| 禄劝| 叶城县| 鄂托克前旗|