docker run시 컨테이너 내의 파일 수정하기(환경변수 +  sed명령어)
42Seoul/웹서버

docker run시 컨테이너 내의 파일 수정하기(환경변수 + sed명령어)

이전에 작성한 글에서 컨테이너에 환경변수를 선언하고 사용하는 법은 간단하게 설명하였습니다. 이번에는 환경변수와 sed -i명령어를 활용하여, docker run시 설정한 환경변수 값에 따라, 컨테이너에 위치할 파일의 내용을 수정해 보겠습니다.

 

이를 응용하면, nginx의 default 파일 내용을 환경변수 값에 따라 수정하여, nginx의 설정을 변경하는 것과 같은 작업도 할 수 있습니다.

 

 

sed 명령어

sed 명령어는 다음과 같이 사용할 수 있습니다. -i 옵션을 주지 않을 경우, 실제 파일의 내용은 수정되지 않습니다.

sed -i "s/찾을 문자열/바꿀 문자열/" 파일경로

 

 

 

파일 수정 예제

환경변수 HELLO의 옵션에 따라, hello.txt의 내용을 변경하는 예제를 작성해보았습니다.

 

 srcs/hello.txt

hello

 

 srcs/change_option.sh

#!/bin/bash
if [ "$HELLO" == "on" ];then
	sed -i "s/hello/I want to say hello/" /root/hello.txt
else
	sed -i "s/hello/I don't want to say hello/" /root/hello.txt
fi

cat /root/hello.txt

도커 파일에서 실행할 스크립트입니다. 환경변수 값에 따라 hello.txt의 내용을 변경하고, cat으로 출력합니다. 쉘 스크립트에서 if문을 사용할 때, [] 괄호 안의 양쪽 끝에는 반드시 공백이 있어야 합니다.

 

 Dockerfile

FROM debian:buster

MAINTAINER Lee Sujeong <sujlee@student.42seoul.kr>

ENV HELLO "off"

RUN apt-get update
RUN apt-get upgrade -y

COPY srcs/hello.txt /root/
COPY srcs/change_option.sh /root/
CMD ["/bin/bash", "/root/change_option.sh"]

EXPOSE 80

 

 

 

실행

-e 옵션으로 환경 변수의 값을 변경하여, hello.txt의 내용을 수정할 수 있습니다.

docker build . -t envtest
docker run -it -p 80:80 -e HELLO="on" envtest