DockerfileでUSERを利用する
Docker docker-compose
Published: 2020-12-23

やったこと

DockerfileでUSERを使ってみます。

確認環境

$ docker --version
Docker version 19.03.13, build 4484c46d9d
$ docker-compose --version
docker-compose version 1.27.4, build 40524192

調査

docker-compose.yml

version: '3'
services:
  db-master:
    build:
      context: .
      args:
        my_cnf: master.cnf
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes

Dockerfile

FROM mysql:5.6

RUN groupadd -r app && useradd -r -g app app
USER app
COPY ./master.cnf /etc/mysql/conf.d/my.cnf
COPY --chown=app:app ./master.cnf /etc/mysql/conf.d/my2.cnf

master.cnf

[mysqld]
server-id = 1
log_bin = mysql-bin

確認

$ docker-compose run db-master bash
WARNING: Found orphan containers (mysql_db-slave_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
Creating mysql_db-master_run ... done
app@a636617998ba:/$ ls -lh /etc/mysql/conf.d/
total 20K
-rw-r--r-- 1 root root 43 Nov 21 01:23 docker.cnf
-rw-r--r-- 1 root root 43 Dec 20 13:47 my.cnf
-rw-r--r-- 1 app  app  43 Dec 20 13:47 my2.cnf
-rw-r--r-- 1 root root  8 Jul  9  2016 mysql.cnf
-rw-r--r-- 1 root root 55 Jul  9  2016 mysqldump.cnf

my2.cnfapp ユーザーになっていることが分かります。

おまけ

確認したコンテナ環境

$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
VERSION_CODENAME=stretch
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

$ groupadd --help
Usage: groupadd [options] GROUP

Options:
  -r, --system                  create a system account

$ useradd --help
Usage: useradd [options] LOGIN
       useradd -D
       useradd -D [options]

Options:
  -g, --gid GROUP               name or ID of the primary group of the new
                                account
  -r, --system                  create a system account

参考