In Docker, we can pass parameters to a Dockerfile using the ARG instruction. The ARG instruction enables you to define a variable during the Docker image build process, which can be utilized within the Dockerfile or provided externally through the docker build command.
Usage Steps:
-
Define ARG Variables: In the Dockerfile, you can use the
ARGinstruction to define one or more variables. For example:dockerfileFROM ubuntu ARG version ``n This defines a variable named `version`. -
Use Variables in the Dockerfile: After defining variables, you can use them in other parts of the Dockerfile, such as as parameters for other instructions. For example, using the
versionvariable to specify the software version to install:dockerfileRUN apt-get update && apt-get install -y software=${version} ``n -
Pass Parameters During Build: When building a Docker image, you can pass parameters using the
--build-argoption. For example:bash
docker build --build-arg version=1.2.3 -t myimage .
``n
This command passes 1.2.3 as the value for the version parameter to the Dockerfile and builds an image tagged as myimage.
Example Usage:
Suppose we need to build a Docker image for a Node.js application and want to specify the Node.js version. We can set up the Dockerfile as follows:
dockerfile# Specify the base image FROM node:12 # Define the Node.js version as a variable ARG NODE_VERSION=12 # Set environment variables ENV NODE_VERSION $NODE_VERSION # Install necessary packages and configure RUN npm install # Copy application code into the container COPY . /app # Run the application CMD ["node", "/app/index.js"]
When building this image, if you need to use Node.js 14, you can build it as:
bashdocker build --build-arg NODE_VERSION=14 -t mynodeapp .
This approach achieves dynamic parameter passing and usage during the build process through ARG and --build-arg. It enhances the flexibility and configurability of the Dockerfile, making it ideal for multi-environment or multi-version scenarios.