Table of Contents
#Introduction
In this tutorial, How to Pass environment variables to Docker containers. You need to pass environment variables to docker containers as a running instance of Docker. I use Docker images Postgres Databases.
Set environment variables to Docker containers
We will set a variable DB_USER and DB_PASSWORD as follows:
export POSTGRES_PASSWORD=123456789
export POSTGRES_USER=devopsroles
To verify variable has been set as command follows:
echo $POSTGRES_USER
echo $POSTGRES_PASSWORD
The output terminal is as follows:
[vagrant@localhost ~]$ export POSTGRES_PASSWORD=123456789
[vagrant@localhost ~]$ export POSTGRES_USER=devopsroles
[vagrant@localhost ~]$ echo $POSTGRES_USER
devopsroles
[vagrant@localhost ~]$ echo $POSTGRES_PASSWORD
123456789
Pass the variable to a container
docker run --name postgresql -e POSTGRES_PASSWORD -e POSTGRES_USER -d postgres
The output terminal is as follows:
[vagrant@localhost ~]$ docker run --name postgresql -e POSTGRES_PASSWORD -e POSTGRES_USER -d postgres
142c69e2f3e2d1ec5c55431877ebaa55d92395399aadbcdf572c7eae201cd378
[vagrant@localhost ~]$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
142c69e2f3e2 postgres "docker-entrypoint.s…" 4 seconds ago Up 3 seconds 5432/tcp postgresql
[vagrant@localhost ~]$ docker exec -it postgresql /bin/bash
root@142c69e2f3e2:/# env | egrep "POSTGRES_PASSWORD|POSTGRES_USER"
POSTGRES_PASSWORD=devopsroles
POSTGRES_USER=123456789
root@142c69e2f3e2:/# exit
exit
[vagrant@localhost ~]$ docker exec -it postgresql psql -U $POSTGRES_USER
psql (13.4 (Debian 13.4-1.pgdg100+1))
Type "help" for help.
123456789=#
Pass variables with an .env file
I will create a new .env file with the command:
vi .env
Copy and paste content as follows:
POSTGRES_PASSWORD=123456789
POSTGRES_USER=devopsroles
Save and close the file.
Use docker run the command as follows:
docker run --name postgresql --env-file .env -d postgres
The output terminal is as follows:
[vagrant@localhost ~]$ cat .env
POSTGRES_PASSWORD=123456789
POSTGRES_USER=devopsroles
[vagrant@localhost ~]$ docker run --name postgresql --env-file .env -d postgres
00744474177bb7af571c48dcbb974c2649857413020226a2340cb5411b9034dc
Check it
[vagrant@localhost ~]$ docker exec -it postgresql /bin/bash
root@00744474177b:/# env | egrep "POSTGRES_PASSWORD|POSTGRES_USER"
POSTGRES_PASSWORD=123456789
POSTGRES_USER=devopsroles
root@00744474177b:/#
Via Youtube
Conclusion
You have to Pass environment variables to Docker containers. I hope will this your helpful. Thank you for reading the DevopsRoles page!