You can use the ARG command inside a Dockerfile to define the name of a parameter and its default value. This default value can also be overridden using a simple option with the Docker build command. The difference between ENV and ARG is that after you set an environment variable using ARG, you will not be able to access that later on when you try to run the Docker Container.
In this article, we will discuss how to use the ARG instruction inside a Dockerfile to set parameters. Follow the below steps to implement ARG instruction in a Dockerfile:
Step 1: Write a Dockerfile to build the Image
You can create a Dockerfile with ARG instruction using the following template.
FROM ubuntu:latest ARG GREET=GeeksForGeeks RUN echo "Hey there! Welcome to $GREET" > greeting.txt CMD cat greeting.txt
The above Dockerfile pulls the Ubuntu Base Image from Docker Hub and sets a parameter called GREET to GeeksForGeeks. It then uses the parameter to create a text file and then prints the message inside the text file.
Step 2: Build the Docker Image
You can build the Docker Image using the following command.
sudo docker build -t arg-demo .
Step 3: Run the Docker Container
To run the Docker Container, you can use the following Docker Run command.
sudo docker run -it arg-demo bash
You can see that the file greetings.txt has been created with the message created using the parameter GREET.
Step 4: Overriding the ARG default value
You can override the default value of ARG by using the –build-arg option along with the build command.
sudo docker build -t arg-demo --build-arg GREET=World .
You can now run the container, print the file and you will see the updated message.
To conclude, in this article, we discussed how to use the ARG command to set parameter values to be used throughout the Dockerfile. We also discussed how to override the parameter value using the –build-arg option along with the Docker build command.
Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.