Kuzunoha-NEのブログ

プログラミングなどの勉強をしてます

【DockerCompose】DockerfileのFROMに使える変数の設定

こんばんは、葛の葉です。

DockerfileでFROMに対する変数を入れることで、色々使いまわせます。

docs.docker.com

DockerComposeのargsを使えばこんなこともできます。

ファイル構成

.
├── Dockerfile
└── docker-compose.yml

Dockerfile

ARG Ver
FROM python:$Ver

docker-compose.yml

version: '3'
services:
  test_app:
    build: 
      context: ./
      args:
        Ver: "3.7.3"
    command: python --version

upしてみる。

Creating network "teste_default" with the default driver
Creating teste_test_app_1 ... done
Attaching to teste_test_app_1
test_app_1  | Python 3.7.3
teste_test_app_1 exited with code 0

もう一つServiceを追加して実行する。

docker-compose.yml

version: '3'
services:
  test_app:
    build: 
      context: ./
      args:
        Ver: "3.7.3"
    command: python --version

  test_app2:
    build: 
      context: ./
      args:
        Ver: "3.6.5"
    command: python --version

docker-compose upとしてみる。

Starting teste_test_app_1  ... done
Creating teste_test_app2_1 ... done
Attaching to teste_test_app_1, teste_test_app2_1
test_app_1   | Python 3.7.3
test_app2_1  | Python 3.6.5
teste_test_app_1 exited with code 0
teste_test_app2_1 exited with code 0

結論

ひとつのDockerfileを使いまわして複数のServiceを起動できる。