How do I pass environment variables to Docker containers?

前端 未结 14 1531
独厮守ぢ
独厮守ぢ 2020-11-22 11:15

I\'m new to Docker, and it\'s unclear how to access an external database from a container. Is the best way to hard-code in the connection string?

# Dockerfil         


        
14条回答
  •  青春惊慌失措
    2020-11-22 11:33

    Using docker-compose, you can inherit env variables in docker-compose.yml and subsequently any Dockerfile(s) called by docker-compose to build images. This is useful when the Dockerfile RUN command should execute commands specific to the environment.

    (your shell has RAILS_ENV=development already existing in the environment)

    docker-compose.yml:

    version: '3.1'
    services:
      my-service: 
        build:
          #$RAILS_ENV is referencing the shell environment RAILS_ENV variable
          #and passing it to the Dockerfile ARG RAILS_ENV
          #the syntax below ensures that the RAILS_ENV arg will default to 
          #production if empty.
          #note that is dockerfile: is not specified it assumes file name: Dockerfile
          context: .
          args:
            - RAILS_ENV=${RAILS_ENV:-production}
        environment: 
          - RAILS_ENV=${RAILS_ENV:-production}
    

    Dockerfile:

    FROM ruby:2.3.4
    
    #give ARG RAILS_ENV a default value = production
    ARG RAILS_ENV=production
    
    #assign the $RAILS_ENV arg to the RAILS_ENV ENV so that it can be accessed
    #by the subsequent RUN call within the container
    ENV RAILS_ENV $RAILS_ENV
    
    #the subsequent RUN call accesses the RAILS_ENV ENV variable within the container
    RUN if [ "$RAILS_ENV" = "production" ] ; then echo "production env"; else echo "non-production env: $RAILS_ENV"; fi
    

    This way, I don't need to specify environment variables in files or docker-compose build/up commands:

    docker-compose build
    docker-compose up
    

提交回复
热议问题