How do I pass environment variables to Docker containers?

前端 未结 14 1150
独厮守ぢ
独厮守ぢ 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:41

    we can also you host machine environment variable using -e flag and $ :

    Before running need to export(means set) local env variable and file or just before using

    docker run -it -e MG_HOST=$MG_HOST -e MG_USER=$MG_USER -e MG_PASS=$MG_PASS -e MG_AUTH=$MG_AUTH -e MG_DB=$MG_DB -t image_tag_name_and_version 
    

    By using this method set env variable automatically with your given name in my case(MG_HOST ,MG_USER)

    Additional:

    If you are using python you can access these envment variable inside docker by

    import os
    host,username,password,auth,database=os.environ.get('MG_HOST'),os.environ.get('MG_USER'),os.environ.get('MG_PASS'),os.environ.get('MG_AUTH'),os.environ.get('MG_DB')
    
    0 讨论(0)
  • 2020-11-22 11:42

    If you are using 'docker-compose' as the method to spin up your container(s), there is actually a useful way to pass an environment variable defined on your server to the Docker container.

    In your docker-compose.yml file, let's say you are spinning up a basic hapi-js container and the code looks like:

    hapi_server:
      container_name: hapi_server
      image: node_image
      expose:
        - "3000"
    

    Let's say that the local server that your docker project is on has an environment variable named 'NODE_DB_CONNECT' that you want to pass to your hapi-js container, and you want its new name to be 'HAPI_DB_CONNECT'. Then in the docker-compose.yml file, you would pass the local environment variable to the container and rename it like so:

    hapi_server:
      container_name: hapi_server
      image: node_image
      environment:
        - HAPI_DB_CONNECT=${NODE_DB_CONNECT}
      expose:
        - "3000"
    

    I hope this helps you to avoid hard-coding a database connect string in any file in your container!

    0 讨论(0)
提交回复
热议问题