Docker is an opensource tool used for virtualization and deliver software in the form of packages called Containers. It is one of the most important tools used in networking domain. Dockerfile is a template for building the image which contains commands needed to package the software. In this post, I am going to explain the commands ARG & ENV used in Dockerfile
ARG Command:
ARG command is used to pass the value at build time. Once ARG variable is declared in Dockerfile its scope starts until the end of the build of Dockerfile. Containers built from image will not have ARG variables and their values. There should be space between Key, Operator and Value while defining ARG variables
Scenario: Consider the building of image where we are creating one user and the name of the user is defined at build time. In that case, ARG command will be useful. Look the below lines of Dockerfile for mentioned scenario.
FROM ubuntu:16.04
ARG User
RUN useradd –u 5000 $User
If we do not pass the value for argument, error will be generated while building the image. One can build the image by passing the argument for User using the command docker build <Path_of_Dockerfile> --build-arg User=”Name_Of_User” -t <name_of_image_in_lower_case>.
One can check the arguments and the passed value using command docker history <image_name_or_id>
To provide default value for argument to be used when we don’t provide value during the build the ARG command usage will be
ARG Variable=”Default_Value”
Using ARG command, one can make base image version to be specified at run time
ENV Command:
ENV command is used for setting environment variables. Unlike ARG, its scope is not limited to Dockerfile building the image, it will be present inside containers. There should be space between Key, Operator and Value while defining environment variables
Scenario: Consider a scenario in which container should have a variable name for particular host to check connectivity. In this scenario, ENV command will be useful. Look at the below lines of Dockerfile for mentioned scenario.
FROM ubuntu:16.04
RUN apt-get update && apt-get install iputils-ping –y
ENV Host=”google.com”
Once we build container from image, we can directly ping google.com using ping $Host inside container
One can check the environment variables of the image using docker inspect –format=’{{json .Config.Env}}’ <image_name_or_id>
Comments
Post a Comment