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
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!