ENV and ARG
ENV
If your application has environment variables, you can pass them to a container at startup using the -e key:
docker build . -t web-server:1.1-env
docker run -p 8080:8080 -e APP_ENV=Production web-server:1.1-env
Applications can use these variables somewhere in their code, for example:
from flask import Flask, Response, send_file
import os
app = Flask(__name__)
# Access the environment variable appEnv = os.environ.get("APP_ENV", "Development")
appEnv = os.environ.get("APP_ENV", "Development") #"Development" - default value if APP_ENV is empty
@app.route('/')
def hello():
return "Docker is Awesome! My APP_ENV is {appEnv}"
@app.route('/logo')
def docker_logo():
return send_file('docker-logo.png', mimetype='image/png')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
ARG
The ARG instruction is similar to ENV, but is only available during the Image build and only within the context of the Dockerfile. The application itself does not know about the ARG value, nor does the container.
ARG PYTHIN_VERSION=3.14
FROM python:{$PYTHIN_VERSION}.0a3-alpine3.21
WORKDIR /app
COPY app.py .
COPY docker-logo.png .
COPY requirements.txt .
RUN pip install -r requirements.txt
EXPOSE 8080
ENTRYPOINT ["python", "app.py"]
How is ARG used in practice? For example, our application needs to run on different versions of Python, and we need to distribute it with Images based on different Python versions. We can build the same Dockerfile with different base Python Image versions as follows:
Summary:
- ENV is used to pass configurations into the application itself. For example, a database URL or an external API value.
- ARG is used to set some variable value needed inside the
Dockerfileitself. ARG can be used in otherDockerfileinstructions, such asRUN. You can also override ENV as follows: