Pass CLA of a String into a Docker Image – Python

I am wanting to pass a string into the command line arguments that will set the class within a python file when starting up a docker container. I am using the base image of python:3.9.

How do i pass a CLA of a string when building the docker container

Python Script

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Pass the variable needed')
    parser.add_argument('var', type=str, help='variable')
    args = parser.parse_args()
    ENVPath = '/usr/local/bin/chromedriver'

    if sys.argv[1] == 'prod':
        currentvar = TestPrerequisiteService(ENVPath, prod)

    elif sys.argv[1] == 'test':
        currentvar = TestPrerequisiteService(ENVPath, test)
    else:
        print("Invalid variable")
        exit()

Dockerfile

FROM python:3.9

ADD /app/main.py .
ADD /app/Connect.py .

# Install Chrome WebDriver
RUN CHROMEDRIVER_VERSION=`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE` && 
    mkdir -p /opt/chromedriver-$CHROMEDRIVER_VERSION && 
    curl -sS -o /tmp/chromedriver_linux64.zip http://chromedriver.storage.googleapis.com/$CHROMEDRIVER_VERSION/chromedriver_linux64.zip && 
    unzip -qq /tmp/chromedriver_linux64.zip -d /opt/chromedriver-$CHROMEDRIVER_VERSION && 
    rm /tmp/chromedriver_linux64.zip && 
    chmod +x /opt/chromedriver-$CHROMEDRIVER_VERSION/chromedriver && 
    ln -fs /opt/chromedriver-$CHROMEDRIVER_VERSION/chromedriver /usr/local/bin/chromedriver

# Install Google Chrome
RUN curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && 
    echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list && 
    apt-get -yqq update && 
    apt-get -yqq install google-chrome-stable && 
    rm -rf /var/lib/apt/lists/*

COPY requirements.txt .

RUN pip install -r requirements.txt

WORKDIR /microservices

COPY ./app ./app


CMD ["python","./app/main.py"]

Some help would be much appreciated 🙂

Answer

CMD defines the arguments passed to the ENTRYPOINT of the container. I believe the current ENTRYPOINT of your container is /bin/sh which takes ["python","./app/main.py"] as arguments. When you run the container with docker run -p 5000:5000 microservicestesting prod, prod overwrites the arguments defined in the dockerfile with CMD.

To get the functionality you want change CMD to ENTRYPOINT, then when you run the docker run command prod will be passed as an argument to ["python","./app/main.py"]