简体   繁体   中英

How to pass argument to docker container when running docker-compose up

I have the following Dockerfile:

FROM python:3.6
ADD . /

RUN pip install -r requirements.txt
ENTRYPOINT ["python3.6", "./main.py"]

Where main.py takes in run time arguments that are parsed using argparse like so:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('city')
args = parser.parse_args()
print(args.city)

I have succesfully built a docker image from my Dockerfile and run a container based on this image using:

docker run -it my-docker-image "los angeles"

This works great and argparse in python receives the param "los angeles" as the city in my python code snippet.

I am now trying to accomplish the equivalent of

docker run -it my-docker-image "los angeles"

But with a docker-compose.yml file. Right now my docker-compose.yml file looks like:

version: '3'

services:
  data-worker:
    image: url-to-my-docker-container-on-ecr-that-i-have-pulled-onto-my-local-machine
    container_name: run-for-city
    volumes:
      - ~/.aws/:/root/.aws

I then try running:

docker-compose up

and it gets started but fails saying:

run-for-city | usage: main.py [-h] city
run-for-city | main.py: error: the following arguments are required: city
run-for-city exited with code 2

which makes perfect sense as i need to pass the city param when running docker-compose up but don't know exactly how to.

i tried:

docker-compose up "los angeles" 

but that did not work.

Do i need to add something to my docker-compose.yml and or an argument to the docker-compose up command or what?

In Docker terminology, the extra parameter you're passing is a "command". (Anything after the image name in docker run is the command; conventionally it's an actual command to run, but if you have an ENTRYPOINT in your Dockerfile, it's passed as arguments to the entrypoint.) You can replicate this in your docker-compose.yml file:

version: '3'
services:
  data-worker:
    image: 123456789012.dkr...
    volumes:
      - ~/.aws/:/root/.aws
    command: ["los angeles"]  # <--

If you need to pass this at the command line, the only real way to do it is via an environment variable. Compose will substitute environment variables (note, somewhat limited syntax) and I believe it will work to say

command: ["$CITY"]

and you'd launch this with

CITY="los angeles" docker-compose up

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM