Docker 컨테이너에 환경 변수를 전달하려면 어떻게해야합니까?
저는 Docker를 처음 사용하며 컨테이너에서 외부 데이터베이스에 액세스하는 방법이 명확하지 않습니다. 연결 문자열에서 하드 코딩하는 가장 좋은 방법은 무엇입니까?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
-e
플래그 를 사용하여 환경 변수를 컨테이너에 전달할 수 있습니다 .
시작 스크립트의 예 :
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
당신이 그것을에 의해 표시되는 명령 줄에 값이하지 않으려는 경우 또는, ps
등, -e
당신은 단지없이 줄 경우 현재 환경의 값에 당길 수 =
:
sudo PASSWORD='foo' docker run [...] -e PASSWORD [...]
환경 변수가 많고 특히 비밀을 의미 하는 경우 env-file을 사용할 수 있습니다 .
$ docker run --env-file ./env.list ubuntu bash
--env-file 플래그는 파일 이름을 인수로 사용하고 각 행이 --env에 전달 된 인수를 모방하여 VAR = VAL 형식이 될 것으로 예상합니다. 주석 줄에는 # 접두사 만 있으면됩니다.
여기 에서 언급하고 @errata에서 언급 한대로 명령과 -e
함께 매개 변수를 사용하여 전달할 수 있습니다 . 그러나이 방법의 가능한 단점은 자격 증명이 실행되는 프로세스 목록에 표시된다는 것입니다. 더 안전하게 보호하려면 구성 파일에 자격 증명을 작성하고 수행 할 수 있습니다 에 언급 한 바와 같이 여기 . 그런 다음 해당 컴퓨터에 액세스하는 다른 사용자가 사용자의 자격 증명을 볼 수 없도록 해당 구성 파일의 액세스를 제어 할 수 있습니다.docker run ..
docker run
--env-file
컨테이너를 회전시키는 방법으로 'docker-compose'를 사용하는 경우 실제로 서버에 정의 된 환경 변수를 Docker 컨테이너에 전달하는 유용한 방법이 있습니다.
당신의에서 docker-compose.yml
파일의 당신이 기본 게요!-JS 컨테이너와 코드를 보이는 등을 회전하는 가정 해 봅시다 :
hapi_server:
container_name: hapi_server
image: node_image
expose:
- "3000"
도커 프로젝트가있는 로컬 서버에 hapi-js 컨테이너에 전달하려는 'NODE_DB_CONNECT'라는 환경 변수가 있고 새 이름이 'HAPI_DB_CONNECT'가되기를 원한다고 가정 해 보겠습니다. 그런 다음 docker-compose.yml
파일에서 로컬 환경 변수를 컨테이너에 전달하고 다음과 같이 이름을 바꿉니다.
hapi_server:
container_name: hapi_server
image: node_image
environment:
- HAPI_DB_CONNECT=${NODE_DB_CONNECT}
expose:
- "3000"
컨테이너의 모든 파일에서 데이터베이스 연결 문자열을 하드 코딩하는 것을 방지하는 데 도움이되기를 바랍니다.
Use -e
or --env value to set environment variables (default []).
시작 스크립트의 예 :
docker run -e myhost='localhost' -it busybox sh
명령 줄에서 여러 환경을 사용하려면 모든 환경 변수를 사용하기 전에 -e
flag.
예:
sudo docker run -d -t -i -e NAMESPACE='staging' -e PASSWORD='foo' busybox sh
참고 : 컨테이너 이름은 환경 변수 앞이 아닌 뒤에 넣어야합니다.
많은 변수를 설정해야하는 경우 --env-file
flag
예를 들면
$ docker run --env-file ./my_env ubuntu bash
다른 도움이 필요하면 Docker 도움말을 살펴보세요.
$ docker run --help
Official documentation: https://docs.docker.com/compose/environment-variables/
Using docker-compose
, the example below shows how you can inherit shell env variables within both docker-compose.yml and in turn any Dockerfile(s) called by docker-compose
to build images. I've found this useful if say in the Dockerfile
RUN
command I need to execute commands specific to the environment.
(your shell has RAILS_ENV=development
already existing in the environment)
docker-compose.yml:
version: '3.1'
services:
my-service:
build:
#$RAILS_ENV is referencing the shell environment RAILS_ENV variable
#and passing it to the Dockerfile ARG RAILS_ENV
#the syntax below ensures that the RAILS_ENV arg will default to
#production if empty.
#note that is dockerfile: is not specified it assumes file name: Dockerfile
context: .
args:
- RAILS_ENV=${RAILS_ENV:-production}
environment:
- RAILS_ENV=${RAILS_ENV:-production}
Dockerfile:
FROM ruby:2.3.4
#give ARG RAILS_ENV a default value = production
ARG RAILS_ENV=production
#assign the $RAILS_ENV arg to the RAILS_ENV ENV so that it can be accessed
#by the subsequent RUN call within the container
ENV RAILS_ENV $RAILS_ENV
#the subsequent RUN call accesses the RAILS_ENV ENV variable within the container
RUN if [ "$RAILS_ENV" = "production" ] ; then echo "production env"; else echo "non-production env: $RAILS_ENV"; fi
This way I dont need to specify environment variables in files or docker-compose
build
/up
commands:
docker-compose build
docker-compose up
There is a nice hack how to pipe host machine environment variables to a docker container:
env > env_file && docker run --env-file env_file image_name
Use this technique very carefully, because
env > env_file
will dump ALL host machine ENV variables toenv_file
and make them accessible in the running container.
For Amazon AWS ECS/ECR, you should manage your environment variables (especially secrets) via a private S3 bucket. See blog post How to Manage Secrets for Amazon EC2 Container Service–Based Applications by Using Amazon S3 and Docker.
Another way is to use the powers of /usr/bin/env
:
docker run ubuntu env DEBUG=1 path/to/script.sh
If you have the environment variables in an env.sh
locally and want to set it up when the container starts, you could try
COPY env.sh /env.sh
COPY <filename>.jar /<filename>.jar
ENTRYPOINT ["/bin/bash" , "-c", "source /env.sh && printenv && java -jar /<filename>.jar"]
This command would start the container with a bash shell (I want a bash shell since source
is a bash command), sources the env.sh
file(which sets the environment variables) and executes the jar file.
The env.sh
looks like this,
#!/bin/bash
export FOO="BAR"
export DB_NAME="DATABASE_NAME"
I added the printenv
command only to test that actual source command works. You should probably remove it when you confirm the source command works fine or the environment variables would appear in your docker logs.
Using jq to convert the env to JSON:
env_as_json=`jq -c -n env`
docker run -e HOST_ENV="$env_as_json" <image>
this requires jq version 1.6 or newer
this pust the host env as json, essentially like so in Dockerfile:
ENV HOST_ENV (all env from the host as json)
'program tip' 카테고리의 다른 글
Android 8 : 일반 텍스트 HTTP 트래픽이 허용되지 않음 (0) | 2020.09.30 |
---|---|
jQuery Ajax 오류 처리, 사용자 정의 예외 메시지 표시 (0) | 2020.09.30 |
자바 스크립트가 변수로 개체 키 설정 (0) | 2020.09.29 |
Java에 파일이 있는지 어떻게 확인합니까? (0) | 2020.09.29 |
문자를 문자열로 변환하는 방법? (0) | 2020.09.29 |