Use Environment Variables for Docker Containers

Joel Lord
InstructorJoel Lord
Share this video with your friends

Social Share Links

Send Tweet

First, we'll see how you can have different run-times installed in a docker container that isn't dependent on your system's current installs. You don't need anything but docker to run these containers! We will demonstrate this by installing the latest version of Node.js in a docker container and compare that to the version of Node.js I'm running on my machine.

Next, you'll see how to pass environment variables to containers. This is important because you will use these variables for API calls as well as configuring databases, and more!

Joel Lord: [0:00] You can also use much more complex containers. In this case, we had a container with a simple operating system, but a lot of containers will include a bunch of executables and runtimes. You could, for example, start a container that has the latest version of Node.js installed by running an image called Node.

[0:21] Just like in our previous examples, you can specify a command to be executed once our container is started. In this case, you will ask Node.js to evaluate the following statement, console.log(process.version). This will start the container, execute the command, and you should see a version number as the output.

[0:45] Note that if you run node -v in your local environment, you might have a different version number. This is because the runtime for Node.js that ran that first command is not the same as the one that you have installed on your machine. In fact, you don't even need to have Node.js installed at all to run Node as long as you have Docker.

[1:08] This can be very useful if you want to share your code with another team for testing purposes. It doesn't matter what runtimes they have installed on their laptop. By using a Docker command, you'll be able to specify what runtimes to use to execute your code.

[1:24] Another neat thing that you can do with containers is to pass environment variables to your container. This way, you can pass it something like the baseURL for your API. Your development team would then be able to use a different API than your production server. To pass an environment variable to your container you can use the -e argument.

[1:47] In this next example, we'll use a docker run. We will use the -e flag to specify an environment variable called name, and we'll call it "World." We will use the base image node:latest, and we will run node -e to evaluate console.log('Hello ' + process.env.name). This is how you access an environment variable inside a Node.js application.

[2:22] If we run this, we should see the output "Hello World." If we take that same example but change the environment variable here to Joel, you should see "Hello Joel."