Docker is used widely nowadays, One can use an already available docker image or can customize it using its own requirements.
Among that, One scenario arises where you have made a custom Dockerfile for different environment deployment, in that case, your environment variable differs but other things remain the same. At that point in time, if you want to pass any variable while creating a Docker image from Dockerfile, Read this article.
For example, a variable that changes multiple times, environment file name or configuration file name for production and development environment.
Passing a variable as an argument help you achieve that. Defining the value of that variable on go.
Let’s see how to achieve that
You can visit our previous article to understand how to create basic Dockerfile
Let’s take an example of Dockerfile, that adds Jar file of Java Spring Code and executes jar file when we run that docker image
FROM openjdk:8-jre ARG profile_name ENV profile $profile_name ADD projectname-0.0.1-SNAPSHOT.jar app.jar ENV JAVA_OPTS="-XX:+UseG1GC -XX:MaxRAM=1024M -Xmx400m" EXPOSE 8000 ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -Dspring.profiles.active=$profile -jar /app.jar
Save above file as “Dockerfile”
In Above Dockerfile,
1. On line number 2, we have defined one variable as ARG named profile_name
–> when we build this docker image, we can pass the value of this parameter as an argument
After that, create a docker image from Dockerfile
docker build --build-arg profile_name=development -t image_name .
Above command is executed in the same directory where Dockerfile resides
Now, you can change the value of profile_name as per your environment,
For an instance, development or production
Dockerfile for both of them will remain the same.
Similarly, you can pass any variable-name as above and define their value on runtime.
Do Reach out in the comment section if you find this content useful and/or have some doubts.
Drafted on: 16th May 2020