Docker ENV, ARG commands
to set ports
Let’s take for example a simple Flask app, for which we know that:
- It starts by default on port 5000
- We can change the default port using the env var FLASK_RUN_PORT, e.g. start the app on port 8000
export FLASK_RUN_PORT=8000
$ flask run
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:8000
Press CTRL+C to quit
The app:
#!/usr/bin/env python
# encoding: utf-8
import json
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
"""return hello world text in bold"""
return '<p><b>Hello World Python!</b></p>'
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
A simple Dockerfile to containerize the app:
FROM python:3-alpine
# copy just the requirements.txt first to leverage Docker cache
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN pip install -r requirements.txt
COPY . /app
CMD ["flask", "run", "--host=0.0.0.0"]
Now let’s play with ENV and ARG and applications port
- Hardcode the port into the image, by using ENV command in the Dockerfile to set the environment variable.
# hardcode the port
ENV FLASK_RUN_PORT=5555
Build the image docker build -t dejanu/python_hello:1.0 .
and run it : docker run --rm -p 5555:5555 dejanu/python_hello:1.0
- Set the port to be passed as env var when the container is started, by using ENV command with the value as a variable, set the var in the Dockerfile:
# pass as env var at runtime
ENV FLASK_RUN_PORT=${FLASK_RUN_PORT}
Build the image docker build -t dejanu/python_hello:1.1 .
and run it : docker run --rm -e FLASK_RUN_PORT=5554 -p 5554:5554 dejanu/python_hello:1.1
- Last but not least as build arguments, if you want the possibility to change the port at build-time, use ARG command in the Dockerfile:
ARG PORT
ENV FLASK_RUN_PORT $PORT
Build the image docker build --build-arg PORT=5553 -t dejanu/python_hello:1.2 .
and run it: docker run — rm -p 5553:5553 dejanu/python_hello:1.2
This is just one small use case for ENV and ARG commands, an important aspect is that if you choose ARG, you can’t change it later during the run, because values of ARGs are not available after the image is built, as you can’t access them anymore once the image is built. However, if you chose ENV you can modify the value when you spin up the container.