No Docker, você pode definir variáveis de ambiente para contêineres, permitindo que você passe configurações e parâmetros para a aplicação em execução dentro do contêiner. Essas variáveis podem ser definidas de várias maneiras, dependendo de como você está criando ou iniciando o contêiner.
Definindo Variáveis de Ambiente na Linha de Comando
A maneira mais comum de definir variáveis de ambiente ao iniciar um contêiner é usando a opção -e ou --env.
Exemplo:
docker container run -e "VAR1=valor1" -e "VAR2=valor2" ubuntu env
Neste exemplo:
-e "VAR1=valor1": Define a variável de ambiente VAR1 com o valor valor1.
-e "VAR2=valor2": Define a variável de ambiente VAR2 com o valor valor2.
ubuntu env: Inicia um contêiner com a imagem ubuntu e executa o comando env para listar todas as variáveis de ambiente dentro do contêiner.
Usando um Arquivo .env
Se você tiver muitas variáveis de ambiente para definir, pode ser mais prático usar um arquivo .env. Este arquivo contém as variáveis de ambiente em formato chave=valor.
Exemplo de Arquivo .env:
VAR1=valor1
VAR2=valor2
Comando para Usar o Arquivo .env:
docker container run --env-file ./minhas_variaveis.env ubuntu env
Aqui:
--env-file ./minhas_variaveis.env: Carrega as variáveis de ambiente do arquivo minhas_variaveis.env.
Definindo Variáveis de Ambiente no Dockerfile
Você também pode definir variáveis de ambiente diretamente no Dockerfile usando a instrução ENV. Isso é útil para criar imagens Docker que já têm certas variáveis de ambiente configuradas.
Exemplo de Dockerfile:
FROM ubuntu
ENV VAR1=valor1
ENV VAR2=valor2
Neste exemplo:
ENV VAR1=valor1: Define a variável VAR1 dentro do contêiner.
ENV VAR2=valor2: Define a variável VAR2 dentro do contêiner.
Acessando Variáveis de Ambiente em um Contêiner
Dentro de um contêiner, você pode acessar as variáveis de ambiente como faria normalmente em um sistema operacional, utilizando comandos como echo ou acessando-as diretamente em scripts ou programas.
Exemplo:
echo $VAR1
Usos Comuns
Configuração de Aplicativos: Muitas vezes, variáveis de ambiente são usadas para passar configurações como credenciais de banco de dados, URLs de serviços externos, e outros parâmetros de configuração.
Chaves Secretas: Variáveis de ambiente são uma prática comum para armazenar chaves de API e outros dados sensíveis, embora seja importante tomar precauções para evitar que esses dados sejam expostos.
Laboratório
As variáveis de ambiente servem para configurar os containeres.
O container não está em execução. Status: Exited (1)
$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
$ docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
08790fce4b9e mysql "docker-entrypoint.s…" 35 seconds ago Exited (1) 33 seconds ago eloquent_dewdne
Visualizar os logs do container:
$ docker logs 08790fce4b9e
2024-08-17 21:36:19+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 9.0.1-1.el9 started.
2024-08-17 21:36:19+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2024-08-17 21:36:19+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 9.0.1-1.el9 started.
2024-08-17 21:36:19+00:00 [ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
You need to specify one of the following as an environment variable:
- MYSQL_ROOT_PASSWORD
- MYSQL_ALLOW_EMPTY_PASSWORD
- MYSQL_RANDOM_ROOT_PASSWORD
Faz-se necessário especificar as variáveis de ambiente para configurar o container. No Docker Registry (Hub) é possível consultar as variáveis de ambiente possíveis à configuração do container:
Environment Variables
When you start the mysql image, you can adjust the configuration of the MySQL instance by passing one or more environment variables on the docker run command line. Do note that none of the variables below will have any effect if you start the container with a data directory that already contains a database: any pre-existing database will always be left untouched on container startup.
MYSQL_ROOT_PASSWORD
This variable is mandatory and specifies the password that will be set for the MySQL root superuser account. In the above example, it was set to my-secret-pw.
MYSQL_DATABASE
MYSQL_USER, MYSQL_PASSWORD
These variables are optional, used in conjunction to create a new user and to set that user's password. This user will be granted superuser permissions (see above) for the database specified by the MYSQL_DATABASE variable. Both variables are required for a user to be created.
Do note that there is no need to use this mechanism to create the root superuser, that user gets created by default with the password specified by the MYSQL_ROOT_PASSWORD variable.
MYSQL_ALLOW_EMPTY_PASSWORD
This is an optional variable. Set to a non-empty value, like yes, to allow the container to be started with a blank password for the root user. NOTE: Setting this variable to yes is not recommended unless you really know what you are doing, since this will leave your MySQL instance completely unprotected, allowing anyone to gain complete superuser access.
MYSQL_RANDOM_ROOT_PASSWORD
This is an optional variable. Set to a non-empty value, like yes, to generate a random initial password for the root user (using pwgen). The generated root password will be printed to stdout (GENERATED ROOT PASSWORD: .....).
MYSQL_ONETIME_PASSWORD
Sets root (not the user specified in MYSQL_USER!) user as expired once init is complete, forcing a password change on first login. Any non-empty value will activate this setting. NOTE: This feature is supported on MySQL 5.6+ only. Using this option on MySQL 5.5 will throw an appropriate error during initialization.
MYSQL_INITDB_SKIP_TZINFO
By default, the entrypoint script automatically loads the timezone data needed for the CONVERT_TZ() function. If it is not needed, any non-empty value disables timezone loading.
Criação do container com as variáveis de ambiente:
$ docker container run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD="root123" -e MYSQL_DATABASE=laborato
rio -e MYSQL_USER=laboratorio -e MYSQL_PASSWORD=laboratorio mysql
67fd9211615eca5b63059e49041b719fb222a87373a8291c519b673760cba36b
$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
67fd9211615e mysql "docker-entrypoint.s…" 43 seconds ago Up 42 seconds 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp frosty_jackson
See also for documentation of environment variables which MySQL itself respects (especially variables like MYSQL_HOST, which is known to cause issues when used with this image).
This variable is optional and allows you to specify the name of a database to be created on image startup. If a user/password was supplied (see below) then that user will be granted superuser access () to this database.