LoginSignup
18
17

More than 3 years have passed since last update.

docker で nginx を root ユーザー以外で起動する

Last updated at Posted at 2018-11-26

コンテナ内で実行するプロセスを root ユーザで実行しないようにしたいときのメモ。

root ユーザーに実行するケース

次の例は nginx の master プロセスは root ユーザー、 worker プロセスは nginx ユーザーで実行される。

FROM nginx

COPY ./nginx.conf /etc/nginx/nginx.conf

CMD ["nginx"]
user nginx;
worker_processes 1;
daemon off;

error_log   /var/log/nginx/error.log warn;
pid         /var/run/nginx.pid;

events {
  worker_connections  1024;
  multi_accept on;
}

http {  
  •••

  server {
    listen      80;
    server_name _;
    charset     utf-8;

    location / {
      try_files $uri @app;
    }

    location @app {
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://hogehoge.com:3000;
    }

  }
}

nginx ユーザーで実行するケース

次の例は nginx の master プロセスと worker プロセス両方を nginx ユーザーで実行されるようにする

nginx ユーザーは nginx イメージで作成されているのでそれを使う。
基本的に well-known port 0〜1023 は root ユーザーでしか使えないため、listen するポートが 80 だと権限エラー bind() to 0.0.0.0:80 failed (13: Permission denied) になる。

listen するポートは 80 から 8080 に変更する。

FROM nginx

COPY ./nginx.conf /etc/nginx/nginx.conf

# 追加
# ディレクトリオーナーを変更
RUN touch /var/run/nginx.pid && \
  chown -R nginx:nginx /var/run/nginx.pid && \
  chown -R nginx:nginx /var/cache/nginx

# 追加
# uid=100(nginx) gid=101(nginx) groups=101(nginx)
USER nginx

CMD ["nginx"]
worker_processes 1;
daemon off;

error_log   /var/log/nginx/error.log warn;
pid         /var/run/nginx.pid;

events {
  worker_connections  1024;
  multi_accept on;
}

http {  
  •••

  server {
    # 変更
    listen      8080;
    server_name _;
    charset     utf-8;

    location / {
      try_files $uri @app;
    }

    location @app {
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://your-app-domain.com:3000;
    }

  }
}
18
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17