SoFunction
Updated on 2025-03-09

Environment variable problem in docker-compose

docker-compose environment variables

The configurations that must be modified for each deployment are independent from the delivery file, and the original configuration is overwritten by docker-compose.

Record it for reference

[root@test03 test]# cat  
version: '2'
services:
  mysql:
    image: test_db:v1
    container_name: xx-mysql
    restart: always
    networks:
      - nets
    environment:
      - MYSQL_ROOT_PASSWORD=xxx0209
    ports:
      - 3306:3306
    volumes:
      - /opt/data/mysql:/var/lib/mysql:z
  redis:
    image: test_redis:v1
    container_name: xx-redis
    restart: always
    networks:
      - nets
    ports:
      - 6379:6379
  admin:
    image: test_admin:v1
    container_name: xx-admin
    restart: always
    # Use nets network    networks:
      - nets
    env_file:
      - ./.env
    environment:
      # Refer to environment variables, and finally pass it into the start command of the delivery in the container      # Example java -jar -=file:/dev/./urandom -=GMT+08 -Xmx1433m -=http://10.90.2.103:8080 ./      - JAVA_OPTS=-=GMT+08 ${Xmx} -D${inter}
    depends_on:
      - mysql
      - redis
    ports:
      - ${pub_port}:8015
# Create a custom networknetworks:
  nets:
    external: false

The name defined by container_name when the application interaction is used by container_name

Xmx,inter,pub_port are the environment variables I use. By looking up the documentation, the variables can be defined in a file, such as defined in .env, as follows:

[root@test03 test]# cat .env 
# memory
Xmx=-Xmx1433m
# open ports
pub_port=8080
# inter 
inter==http://10.90.2.103:8080

Notice:

The environment variables defined in env_file and environment are passed to containers instead of environment variables in them.

The environment variable ${VARIABLE:-default} in the reference is defined in .env or exported from the same shell

You can check that the variable has been referenced through the command

[root@test03 test]# docker-compose config
...
    environment:
      JAVA_OPTS: -=GMT+08 -Xmx1433m -=http://10.90.2.103:8080
...

It is recommended that the file name introduced by env_file is .env, it is best not to use other names.

  • advantage:

.env file changes will update references in docker-compose in real time, using other names will not update references in docker-compose in real time, and using other names to references in docker-compose will sometimes

WARNING: The DB_DIR variable is not set. Defaulting to a blank string.

  • shortcoming:

Customized name is inconvenient

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.