Skip to content

Commit b626eac

Browse files
Add env vars section
1 parent 278529d commit b626eac

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

docs/container/env_vars.md

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
An environment variable consists of a variable name and its value.
2+
3+
There are two ways to set environment variables for a docker container: with CLI arguments, using an _env_ file.
4+
5+
### CLI arguments
6+
7+
When we launch our Docker container, **we can pass environment variables as key-value pairs directly into the command line** using the parameter _–env_ (or its short form _-e_).
8+
9+
For instance, let's execute the following command:
10+
11+
```
12+
$ docker run --rm --env VARIABLE1=foobar alpine env
13+
```
14+
15+
The environment variables we set will be printed to the console:
16+
17+
```
18+
VARIABLE1=foobar
19+
```
20+
21+
As can be seen, the Docker container correctly interprets the variable `VARIABLE1`.
22+
23+
Also, **we can omit the value in the command line if the variable already exists in the local environment**.
24+
25+
For example, let's define a local environment variable:
26+
27+
```
28+
export VARIABLE2=foobar2
29+
```
30+
31+
Then, let's specify the environment variable without its value:
32+
33+
```
34+
docker run --rm --env VARIABLE2 alpine env
35+
```
36+
37+
And we can see Docker still picked up the value, this time from the surrounding environment:
38+
39+
```
40+
VARIABLE2=foobar2
41+
```
42+
43+
### Using --env-file
44+
45+
The above solution is adequate when the number of variables is low. However, as soon as we have more than a handful of variables, it can quickly become cumbersome and error-prone.
46+
47+
**An alternative solution is to use a text file to store our variables**, using the standard _key=value_ format.
48+
49+
Let's define a few variables in a file we'll call _my-env.txt_:
50+
51+
52+
```
53+
$ echo VARIABLE1=foobar1 > my-env.txt
54+
$ echo VARIABLE2=foobar2 >> my-env.txt
55+
$ echo VARIABLE3=foobar3 >> my-env.txt
56+
```
57+
58+
Now, let's inject this file into our Docker container:
59+
60+
```
61+
$ docker run --env-file my-env.txt alpine:3 env
62+
```
63+
64+
Finally, let's take a look at the output:
65+
66+
```
67+
VARIABLE1=foobar1
68+
VARIABLE2=foobar2
69+
VARIABLE3=foobar3
70+
```

mkdocs.yml

+2
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ nav:
3939
- Docker volumes and bind-mounts: 'container/volumes.md'
4040
- Docker volume plugins - an example: 'container/volume_plugin.md'
4141
- Summary: 'container/volume_summary.md'
42+
- Environment variables:
43+
- How to pass env variables to a container: 'container/env_vars.md'
4244
- Docker web UI:
4345
- Portainer: 'gui/portainer.md'
4446

0 commit comments

Comments
 (0)