Containers e variáveis de ambiente

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:

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:

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.

Exemplo com banco de dados MySQL

Execução do container MySQL na porta 3306:

O container não está em execução. Status: Exited (1)

Visualizar os logs do container:

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.

See also https://dev.mysql.com/doc/refman/5.7/en/environment-variables.html⁠ 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).

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

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 (corresponding to GRANT ALL) to this 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:

Acessar o banco de dados com o DBeaver:

Parar e remover o container:

Lembrar que o conteiner é efêmero e que os dados serão perdidos ao remove-lo.

Last updated