Run linux command while creating a envrionment variable during docker compose up

Viewed 24

I want to create an environment variable dynamically, whenever the docker-compose up happens or containers get restarted automatically.

yml file:

web-app:
    build: .
    container_name: abc-server
    ports:
      - "1337:1337"
    volumes:
      - "abc-server-data:/usr/src/app/Volumns"
    env_file:
      - ./abc.config
    environment:
      - HOST_MACHINE_IP_ADDRESS=echo $(hostname -I)
    depends_on:
      mysql:
        condition: service_healthy
    restart: unless-stopped
    secrets:
      - mysql_root_password
      # - server_config

here I want to send HOST_MACHINE_IP_ADDRESS everytime either docker compose up or it automatically restarts

1 Answers

Answer

To create an environment variable dynamically you need a .env file that should also be populated dynamically.

You can use the below command to dynamically pick your host machine's IP address.

echo "HOST_MACHINE_IP_ADDRESS=$(ip -o route get to 8.8.8.8 | sed -n 's/.*src \([0-9.]\+\).*/\1/p')" > .env && sudo docker-compose up

Explanation

The output of $(ip -o route get to 8.8.8.8 | sed -n 's/.*src \([0-9.]\+\).*/\1/p') is your host machine IP address which gets pushed to your .env file together with the 'key' HOST_MACHINE_IP_ADDRESS.

In your yaml file you will have the below.

web-app:
...
    environment:
      - HOST_MACHINE_IP_ADDRESS=${HOST_MACHINE_IP_ADDRESS}
...
Related