将参数传递给 docker 组合

在我的 docker 撰写文件中有一个动态字段,我想在运行期间生成。实际上它是一个字符串模板:

environment:
- SERVER_URL:https://0.0.0.0:${PORT}

我想动态配置这个 PORT参数

docker-compose run <service> PORT=443

文件中有 ARGS参数设置,我想我可以使用。但没有任何信息,我如何使用那些内部撰写文件

151359 次浏览

In docker-compose, arguments are available and usefull only in dockerfile. You can specify what you are doing in the level ahead like following:

#dockerfile
ARG PORT
ENV SERVER_URL "https://0.0.0.0:$PORT"

Your port can be set in your docker-compose.yml:

build:
context: .
args:
- PORT=443

It is actually an environment variable in any case. You can pass it through your run command if that fits to you:

PORT=443 docker-compose run <service>
#or
docker-compose run <service> -e PORT=443

This is possible with docker stack deploy

Example Compose File in your environment section:

- MY_VARIABLE_NAME=${MY_VARIABLE_VALUE}

Stack Deploy Command (I ran this from Gitbash in Windows):

MY_VARIABLE_VALUE=some-value docker stack deploy --compose-file compose_file_here stackname

Reference See this Github post here

You can use the flag when using docker-compose build

docker-compose build --build-arg PRODUCTION=VALUE

In Dockerfile you can get the argument PRODUCTION

# Dockerfile
ARG PRODUCTION
FROM node:latest

This is possible with docker-compose with ARGS inside Dockerfile.

Problem to Solve:

  • Pull changes from Git Respository, to Automate App Deploy

Dockerfile

RUN
ARG CACHEBUST=1 # This will setup a arg called CACHEBUST
RUN  git clone

Run the below bash command to build and run. SETTING --build-arg CACHEBUST= random md5sum hash, makes Docker-Compose to rebuild the image, starting the line with ARGS and so on.

docker-compose -f dockerprd.yml build  --build-arg CACHEBUST=$(echo $RANDOM | md5sum | head -c 20; echo;) && docker-compose -f dockerprd.yml up -d

Sharing the only way I managed to set a runtime variable with Docker Compose using minimum setup and command changes.

On docker-compose.yml:

services:
my_service:
...
environment:
- MYENVVAR=placeholder_value

On the terminal:

docker-compose run -e MYENVVAR=actual_value my_service

Please pay attention that the "-e" portion of the command line argument must come before the service name.

This is described on the official documentation: Set environment variables with docker compose run

The solution that I found for this problem was to dynamically create an env file and pass it as --env-file value.

I created a bash script:

$PROJ=$1
echo "REST_URL=http://$2" > ./docker-env-$PROJ
echo "BRANCH=$3" >> ./docker-env-$PROJ


docker compose \
-p $PROJ \
--env-file ./docker-env-$PROJ \
up -d


rm -f ./docker-env-$PROJ

and run it:

start_all.sh mycont "localhost:8080" master