如何构建一个以非root用户运行的nginx的镜像?


在处理安全问题的时候,想要让nginx以非root用户运行,该如何来操作?

 

可以修改nginx的镜像,按照下面的Dockerfile来构建非root用户运行的nginx镜像

 

FROM中的镜像,是官方下载的基础镜像。

 

创建nginx运行需要的目录,授予对应的用户的权限

 

然后,修改nginx的配置,去掉启动用户的说明

 

如果是nginx用户启动,不是root用户,80端口是不允许使用的,所以修改为1000以上的端口号才行。

FROM 172.20.58.152/middleware/nginx:1.21.4

RUN mkdir -p /var/cache/nginx && chown -R nginx:nginx /var/cache/nginx && \
    mkdir -p /var/log/nginx  && chown -R nginx:nginx /var/log/nginx && \
    mkdir -p /var/lib/nginx  && chown -R nginx:nginx /var/lib/nginx && \
    touch /run/nginx.pid && chown -R nginx:nginx /run/nginx.pid && \
    mkdir -p /etc/nginx/templates /etc/nginx/ssl/certs && \
    chown -R nginx:nginx /etc/nginx && \
    chmod -R 777 /etc/nginx/conf.d && \
    sed -i 's/user  nginx;/#user  nginx;/g' /etc/nginx/nginx.conf && \
    sed -i 's/listen       80;/listen       1080;/g' /etc/nginx/conf.d/default.conf 

USER nginx

EXPOSE 1080

 

 

注意:nginx用户,是镜像中原本就带有的用户。

 

然后,通过docker run -d的方式运行,是可以正常启动的,就可以了

 

[root@nccztsjb-node-23 nginx_nonroot]# docker ps | grep usernginx
1dbb68258813   172.20.58.152/middleware/nginx:1.21.4_usernginx   "/docker-entrypoint.…"   4 minutes ago   Up 4 minutes   80/tcp, 1080/tcp   xenodochial_bartik
[root@nccztsjb-node-23 nginx_nonroot]# 
[root@nccztsjb-node-23 nginx_nonroot]# docker logs 1dbb68258813
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: /etc/nginx/conf.d/default.conf differs from the packaged version
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/07/25 06:58:10 [notice] 1#1: using the "epoll" event method
2023/07/25 06:58:10 [notice] 1#1: nginx/1.21.4
2023/07/25 06:58:10 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2023/07/25 06:58:10 [notice] 1#1: OS: Linux 3.10.0-862.3.3.el7.x86_64
2023/07/25 06:58:10 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 65536:65536
2023/07/25 06:58:10 [notice] 1#1: start worker processes
2023/07/25 06:58:10 [notice] 1#1: start worker process 32
2023/07/25 06:58:10 [notice] 1#1: start worker process 33
2023/07/25 06:58:10 [notice] 1#1: start worker process 34
2023/07/25 06:58:10 [notice] 1#1: start worker process 35
2023/07/25 06:58:10 [notice] 1#1: start worker process 36
2023/07/25 06:58:10 [notice] 1#1: start worker process 37
2023/07/25 06:58:10 [notice] 1#1: start worker process 38
2023/07/25 06:58:10 [notice] 1#1: start worker process 39
[root@nccztsjb-node-23 nginx_nonroot]# 

 

posted @ 2023-07-25 15:04  Zhai_David  阅读(727)  评论(0编辑  收藏  举报