To access environment variables within a Docker container using shell commands, you can follow these steps:
Set Environment Variables: When you run a Docker container, you can set environment variables using the -e
or --env
flag. For example:
docker run -e MY_VARIABLE=example_value -it my_image
Access Environment Variables: Once you’re inside the Docker container, you can use shell commands to access these variables. Here’s how you can do it with different shells:
Bash / Sh: Use the echo
command to display the value of an environment variable.
echo $MY_VARIABLE
Fish: Use the echo
command as well, but access the variable slightly differently.
echo $MY_VARIABLE
List All Environment Variables: If you want to see all the environment variables available in the container, use the env
or printenv
command.
env
# or
printenv
Use Environment Variables in Scripts: You can also use environment variables within scripts that run inside the container. For example, in a bash script:
#!/bin/bash
echo "The value of MY_VARIABLE is: $MY_VARIABLE"
#!/bin/bash
echo "The value of MY_VARIABLE is: $MY_VARIABLE"
Exporting Variables: If you need to set a new environment variable inside the container for use by subsequent commands, use the export
command.
export NEW_VARIABLE="new_value"
Pass Environment Variables from a File: You can also pass environment variables from a file using the –env-file flag when running the container.
docker run --env-file my_env_file.txt -it my_image