Environment variables are crucial in docker as they allow you to configure your application according to your requirements. The following steps will guide you on how to use environment variables in Docker:
Setting environment variables in the Dockerfile:
1. You can use the ENV instruction to set the environment variable in your Dockerfile. For example:
ENV JAVA\_HOME /usr/lib/jvm/java-8-oracle ENV PATH $JAVA\_HOME/bin:$PATH The ENV instruction allows you to set the environment variable to a certain value.Setting environment variables in the Docker run command:
1. You can also set environment variables while running your Docker container. The ‘-e’ option allows you to set the environment variable for this particular need. For example:
docker run -e “env_var_name=another\_value” alpine env In this example, ‘env_var_name’ is your environment variable. This command will run the `env` command in your alpine Docker container with the environment variable ‘env_var_name’ set to ‘another\_value’.Setting environment variables in a .env file:
1. Docker also allows you to declare your environment variables in a .env file. Docker Compose uses this method to set up environment variables. The contents of the .env file should look like this:
ENV_VAR_NAME=env_var_value Then, in your docker-compose.yml file, you can use these variables like this: version: ‘3‘ services: web: build: . environment: – ENV_VAR_NAME This way, Docker Compose will automatically pick up the environment variables declared in your .env file.Using environment variables in Docker is an effective way to keep your application flexible and responsive to changes in your development, staging, and production environments.