Docker Build Arguments and Environment Variables

Docker build arguments

Defining build arguments in Dockerfile

ARG VERSION=0.1
COPY $VERSION .ORCOPY ${VERSION} .
ARG VERSION

Defining build argument in the docker build command

docker build -t hello-world:latest --build-arg version= 0.2 .

Defining multiple docker arguments

ARG VERSION
ARG PORT
docker build -t hello-world:latest --build-arg VERSION=0.2 --build-arg PORT=80 .

Using Build Arguments in the docker-compose file.

ARG VERSION=0.1
ARG PORT=8080
build:
context: .
args:
VERSION: 1
PORT: 9090
build:
context: .
args:
VERSION
PORT

Docker environment variables

process.env.PORT
System.getenv("PORT")

Defining environment variables in Dockerfile

ENV PORT_NUMBER=8080
EXPOSE $PORT_NUMBEROR EXPOSE ${PORT_NUMBER}
ARG PORTENV PORT_NUMBER=$PORT

Defining environment variable in the docker run command

 docker run --env PORT_NUMBER=8080 <image-name>OR docker run -e PORT_NUMBER=8080 <image-name>

Defining multiple environment variables

ENV PORT_NUMBER=8080
ENV HOST_NAME=localhost
ENV DB_NAME=MySQL
docker run -e PORT_NUMBER=8080 -e HOST_NAME=localhost -e DB_NAME= MySQL <image-name>

Environment variable file

PORT_NUMBER=8080
HOST_NAME=localhost
DB_NAME=MySQL
docker run --env-file ./.env <IMAGE-NAME>

Environment variables in the docker-compose file

TAG: 7.3
version: '3'
services:
web:
image: 'webapp:${TAG}'
docker-compose --env-file ./config/.env.dev up docker-compose --env-file ./config/.env.prod up docker-compose --env-file ./config/.env.test up
version:3
services:
node:
environment:
- PORT: 9090
version:3
services:
node:
env_file:
- /config/.env.test
version:3
services:
node:
env_file:
- /config/.env.test1
- /config/.env.test2
version:3
services:
node:
environment:
- PORT
docker-compose run -e PORT=9090 node
docker-compose run -e PORT=9090 node java

Sample Dockerfile using both Build arguments and Environment variable

FROM node:alpine
ARG APP_DIR
WORKDIR $APP_DIR
COPY package.json .
RUN npm install
COPY . .ENV PORT_NUMBER=80
EXPOSE PORT $PORT_NUMBER
CMD ["npm", "install"]

Difference between Build Arguments and Environment variables

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store