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:
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.
Fish: Use the echo
command as well, but access the variable slightly differently.
List All Environment Variables: If you want to see all the environment variables available in the container, use the env
or printenv
command.
Use Environment Variables in Scripts: You can also use environment variables within scripts that run inside the container. For example, in a bash script:
Exporting Variables: If you need to set a new environment variable inside the container for use by subsequent commands, use the export
command.
Pass Environment Variables from a File: You can also pass environment variables from a file using the –env-file flag when running the container.