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
we can also you host machine environment variable using -e flag and $ :
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)
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')
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!