📜  docker run with environment (1)

📅  最后修改于: 2023-12-03 15:14:46.122000             🧑  作者: Mango

Docker Run with Environment

Docker is a popular tool for containerization, and it allows developers to package their applications as containers, making them easy to run, deploy, and move between different environments. One of the most powerful Docker features is the ability to set environment variables when running a container.

Setting Environment Variables

To set environment variables in Docker, you can use the -e or --env flag. For example, to set a variable named DB_HOST with the value localhost, you can use the following command:

docker run --env DB_HOST=localhost your-image

You can also define multiple environment variables by providing multiple -e flags:

docker run \
  --env DB_HOST=localhost \
  --env DB_PORT=5432 \
  --env DB_NAME=mydatabase \
  your-image
Using Environment Variables in Containerized Applications

Once you've set environment variables in your Docker container, they will be available as regular system environment variables in your application. For example, if you're using Node.js, you can access the DB_HOST variable like this:

const host = process.env.DB_HOST;

Similarly, if you're using a web framework like Ruby on Rails, you can access the DB_HOST variable in your database.yml file like this:

default: &default
  adapter: postgresql
  encoding: utf8
  pool: 5
  timeout: 5000
  host: <%= ENV.fetch('DB_HOST', 'localhost') %>
  port: <%= ENV.fetch('DB_PORT', 5432) %>
  database: <%= ENV.fetch('DB_NAME', 'mydatabase') %>
  username: <%= ENV.fetch('DB_USER', 'root') %>
  password: <%= ENV.fetch('DB_PASS', '') %>
Conclusion

Docker run with environment is a powerful feature that allows you to set environment variables in your Docker containers. This makes it easy to run your applications in different environments without having to modify their code. By using environment variables, you can also keep sensitive information, such as passwords and API keys, out of your source code and configuration files.