skip to Main Content

How exactly do we specify the environment variable for docker-compose in the production environment?

For example, below is a snippet of how I have specified my env variables in my current docker-compose file of the development environment:

environment: 
        - REDIS_HOST=redis
        - REDIS_PORT=6379
        - PGUSER=postgres
        - PGHOST=postgres
        - PGDATABASE=postgres
        - PGPASSWORD=postgres_password
        - PGPORT=5432

But I cannot do the same for the production environment as the code would be pushed on GitHub and it would expose the environment variables.

So how exactly do we solve this problem out?

2

Answers


  1. You can put the environment variables in .env file. You will not commit this file in github. It is like a configuration file. To know more about .env file, you can check this:
    https://docs.docker.com/compose/env-file/

    Then you can use the variables in the compose file. You can check it from this:
    https://docs.docker.com/compose/compose-file/#variable-substitution

    Adding with the required answer:
    You can have different values for Environment Variables depending on production or development. You can manage this as well. Try this link:
    https://docs.docker.com/compose/environment-variables/

    you need to run this command to link the environment file with the compose file:

    docker-compose –env-file your_environment_file_location up

    So, for development,

    docker-compose –env-file development_environment_file_location up

    And for production,

    docker-compose –env-file production_environment_file_location up

    hope, this answer will solve your problem.

    Login or Signup to reply.
  2. You can use several ways:

    • One can be to use a .ENV file per environment (which you don´t have to commit of course)

    https://docs.docker.com/compose/environment-variables/#the-env-file

    $ cat .env
    TAG=v1.5
    
    $ cat docker-compose.yml
    version: '3'
    services:
      web:
        image: "webapp:${TAG}"
    

    In this way you can define variables in your Docker Compose file but not the actual values.

    • Other option would be to pass those values for the variables in the Docker Compose command:
    docker-compose run -e DEBUG=1 web python console.py
    

    I personally prefer the first one.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search