Skip to content
Fix Code Error

How do I pass environment variables to Docker containers?

March 13, 2021 by Code Error
Posted By: Anonymous

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?

# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string

Solution

You can pass environment variables to your containers with the -e flag.

An example from a startup script:

sudo docker run -d -t -i -e REDIS_NAMESPACE='staging'  
-e POSTGRES_ENV_POSTGRES_PASSWORD='foo' 
-e POSTGRES_ENV_POSTGRES_USER='bar' 
-e POSTGRES_ENV_DB_NAME='mysite_staging' 
-e POSTGRES_PORT_5432_TCP_ADDR='docker-db-1.hidden.us-east-1.rds.amazonaws.com' 
-e SITE_URL='staging.mysite.com' 
-p 80:80 
--link redis:redis   
--name container_name dockerhub_id/image_name

Or, if you don’t want to have the value on the command-line where it will be displayed by ps, etc., -e can pull in the value from the current environment if you just give it without the =:

sudo PASSWORD='foo' docker run  [...] -e PASSWORD [...]

If you have many environment variables and especially if they’re meant to be secret, you can use an env-file:

$ docker run --env-file ./env.list ubuntu bash

The –env-file flag takes a filename as an argument and expects each line to be in the VAR=VAL format, mimicking the argument passed to –env. Comment lines need only be prefixed with #

Answered By: Anonymous

Related Articles

  • Memcached vs. Redis?
  • Start redis-server with config file
  • From inside of a Docker container, how do I connect to the…
  • Runing vue/cli app under docker simple index.html is opened
  • Docker compose fails to start a service with an error…
  • URL for public Amazon S3 bucket
  • Why am I getting a "401 Unauthorized" error in Maven?
  • Some way to back up and delete an RDS instance, then restore…
  • How to mount host volumes into docker containers in…
  • Can Windows Containers be hosted on linux?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

What’s the syntax for mod in java

Next Post:

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error