Parameters as Environment Variables

In this lesson, you will be introduced to environment variables in the context of containers and learn how to set environment variables in a container.

In real life, a container’s inputs and outputs are likely to vary according to the container’s environment. For instance, if you run a web application, it is likely to connect to a database and listen for incoming requests on a given DNS. The database connection details and DNS will have different values on a development machine, on the test server, and the production server.

Reading a value

Whatever the technology you use inside your container, you can access environment variables. For instance, if you set a name environment variable, you may access it with:

Technology Access
Linux shell $name
.NET Core .AddEnvironmentVariables();
Java System.getenv(“name”)
Node.JS

process.env.name

PHP .$_ENV[“name”]
Python os.environ.get(‘name’)

Providing a value

On a real machine, environment variables are set on your system. Inside a container, they can be set from several sources, which make them appropriate for parameterizing your containers.

In order to provide an environment variable’s value at runtime, you simply use the -e name=value parameter on the docker run command.

A special use case is when the system that runs the container has the name environment variable defined, and you want to reuse it, then you can simply use the -e name parameter without specifying a value.

Default value

You may also want to define a default value for an environment variable, in case it isn’t provided when a container is created; this may be done in the Dockerfile file, using the ENV instruction. For instance, the following makes sure that if the name variable isn’t provided to the docker run command, it has a default value of Dockie:

Get hands-on with 1200+ tech skills courses.