[Docker] Dockerfile 환경 구축 실습

2020. 12. 8. 02:21Docker

1. FastRoute 환경 구축

※ 로컬 환경에 해당 블로그의 'FastRoute (PHP)' 환경 구축을 기준으로 작성되어있습니다.

1) 도커 이미지 생성 및 빌드

설정 파일들을 매번 작성하기 번거롭기 때문에 별도의 파일에 저장하여 관리한다.

// 로컬 PC
srcs
 ㄴㅡ fastrout
      ㄴㅡ phpinfo.php
      ㄴㅡ query.sql
      ㄴㅡ install.sh
      ㄴㅡ Dockerfile
      ㄴㅡ default

 

  • 동작 확인을 위한 파일 : phpinfo.php
  • sql 일괄처리 파일 : query.sql
  • 모든 명령을 처리할 쉘스크립트 : install.sh
  • Dockerfile
  • nginx 설정 파일 : /etc/nginx/site-available/default

- phpinfo.php

<?php phpinfo(); ?>

- query.sql

CREATE DATABASE IF NOT EXISTS TEST;
USE TEST;
DROP TABLE IF EXISTS Test;
CREATE TABLE Test (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(20) NOT NULL COMMENT "name"
);
INSERT INTO Test(name) VALUES ('test');

- install.sh

#!/bin/bash

# 파일 이동
mv /tmp/phpinfo.php /var/www/html
mv /tmp/query.sql /var/www/html

# mysql
service mysql start
mysql -u root --skip-password < /var/www/html/query.sql
echo "CREATE USER 'test'@'localhost' IDENTIFIED BY 'test';" | mysql -u root --skip-password
echo "GRANT ALL PRIVILEGES ON TEST.* TO 'test'@'localhost' IDENTIFIED BY 'test';" | mysql -u root --skip-password
echo "FLUSH PRIVILEGES;"

# 권한 설정
chown -R 775 /var/www/html

# 방화벽 허용
ufw allow 'Nginx HTTP'

# 서비스 시작
service php7.4-fpm start
service nginx start
service mysql restart

bash

※ 글 작성 날짜 기준, php7.4-fpm이 최신이다.

- default

	listen 80 default_server;
	listen [::]:80 default_server;
    
    ...
    
    index index.html index.htm index.nginx-debian.html index.php;
	
    ...
    
    location ~ \.php$ {
		include snippets/fastcgi-php.conf;
	#
		# With php-fpm (or other unix sockets):
		fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
	#	# With php-cgi (or other tcp sockets):
	#	fastcgi_pass 127.0.0.1:9000;
	}

- Dockerfile

# 베이스 이미지 지정
FROM ubuntu:latest 

# 사용자 지정
LABEL maintainer "ozofweird<ozofweird@test.com>"
LABEL title="fastroute" 
LABEL version="0.0" 
LABEL description="fastroute server configuration"

# 타임존 지정
ENV TZ=Asia/Seoul
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# 실행할 명령
RUN apt-get -y update && apt-get -y upgrade
RUN apt-get install -y vim \
    nginx \
    mariadb-server \
    php-fpm \
    php-mysql

# 포트 지정
EXPOSE 80

# 호스트 파일 복사
COPY phpinfo.php ./tmp
COPY query.sql ./tmp
COPY install.sh ./tmp
COPY default ./etc/nginx/sites-available

# 쉘 스크립트 실행
CMD bash /tmp/install.sh

- Dockerfile이 존재하는 폴더 위치에서 실행

docker build -t ozofweird/fastroute:0.0 .

※ Docker Hub에 업로드하기 위해 이미지 생성 시 Docker Hub의 계정명을 앞에 붙여준다.

2) Docker Registry

프라이빗 네트워크에서 구축하기 위해 Docker Store에 공개되어 있는 공식 이미지인 'registry'를 사용한다.

// 도커 레지스트리 검색
docker search registry

// registry 이미지 다운로드
docker image pull registry

// registry 이미지 확인
docker image ls

// registry 이미지 컨테이너 시작
docker container run -d -p 5000:5000 --name registry registry

// registry 컨테이너 확인
docker container ls
// 로컬의 이미지를 localhost:5000에 동작하는 registry에 특정 이름으로 업로드하기 위한 태그 설정
docker image tag fastroute:0.0 localhost:5000/fastroute

// registry에 업로드
docker image push localhost:5000/fastroute

 

 

 

2. Spring 환경 구축 (미해결)

※ CentOS를 베이스 이미지로 구성했습니다.

1) 도커 이미지 생성 및 빌드

// 로컬 PC
srcs
 ㄴㅡ spring
      ㄴㅡ query.sql
      ㄴㅡ install.sh
      ㄴㅡ Dockerfile
      ㄴㅡ default

 

  • sql 일괄처리 파일 : query.sql
  • 모든 명령을 처리할 쉘스크립트 : install.sh
  • Dockerfile
  • nginx 설정 파일 : /etc/nginx/site-available/default
  • 배포 스크립트 : deploy.sh

- query.sql (위와 동일)

-install.sh

#!/bin/bash

# 파일 이동
mv /tmp/query.sql /home
mv /tmp/deploy.sh /home

# mysql
systemctl start mariadb
mysql -u root --skip-password < /home/query.sql
echo "CREATE USER 'test'@'localhost' IDENTIFIED BY 'test';" | mysql -u root --skip-password
echo "GRANT ALL PRIVILEGES ON TEST.* TO 'test'@'localhost' IDENTIFIED BY 'test';" | mysql -u root --skip-password
echo "FLUSH PRIVILEGES;"

# 권한 설정
chmod +x /home/deploy.sh

# 방화벽 허용
firewall-cmd --permanent --zone=public --add-port=8080/tcp
firewall-cmd --reload

# 서비스 시작
systemctl start nginx
systemctl restart mariadb

# 배포 스크립트
./home/deploy.sh

bash

- Dockerfile

# 베이스 이미지 지정
FROM centos:latest 

# 사용자 지정
LABEL maintainer "ozofweird<ozofweird@test.com>"
LABEL title="spring" 
LABEL version="0.0" 
LABEL description="spring server configuration"

# 타임존 지정
ENV TZ=Asia/Seoul
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# 실행할 명령
RUN yum update && yum -y upgrade
RUN yum -y remove java
RUN yum install -y \
    java-1.8.0-openjdk \
    java-1.8.0-openjdk-devel \
    maven \
    curl \
    unzip \
    firewalld \
    git
RUN yum install -y vim \
    nginx \
    mariadb-server
	

# 포트 지정
EXPOSE 8080

# 호스트 파일 복사
COPY query.sql ./tmp
COPY install.sh ./tmp
COPY default ./etc/nginx/sites-available
COPY deploy.sh ./tmp

# 쉘 스크립트 실행
CMD bash /tmp/install.sh

- default

	listen 8080 default_server;
	listen [::]:8080 default_server;
    
    ...
    
    index index.html index.htm index.nginx-debian.html index.php;
	
    ...
    
    location ~ \.php$ {
		include snippets/fastcgi-php.conf;
	#
		# With php-fpm (or other unix sockets):
		fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
	#	# With php-cgi (or other tcp sockets):
	#	fastcgi_pass 127.0.0.1:9000;
	}

- deploy.sh

#!/bin/bash

cd /home
mkdir projects
cd projects
git clone https://github.com/ozofweird/SpringBoot_DockerTest.git

REPOSITORY=$(pwd)

cd $REPOSITORY/SpringBoot_DockerTest/

echo "> Git Pull"

git pull

echo "> 프로젝트 Build 시작"

./gradlew build

echo "> Build 파일 복사"

cp ./build/libs/*.jar $REPOSITORY/

echo "> 현재 구동중인 애플리케이션 pid 확인"

CURRENT_PID=$(pgrep -f SpringBoot_DockerTest)

echo "$CURRENT_PID"

if [ -z $CURRENT_PID ]; then
    echo "> 현재 구동중인 애플리케이션이 없으므로 종료하지 않습니다."
else
    echo "> kill -2 $CURRENT_PID"
    kill -9 $CURRENT_PID
    sleep 5
fi

echo "> 새 어플리케이션 배포"

JAR_NAME=$(ls $REPOSITORY/ |grep 'SpringBoot_DockerTest' | tail -n 1)

echo "> JAR Name: $JAR_NAME"

nohup java -jar $REPOSITORY/$JAR_NAME &

※ 만약 application-oauth.properties 와 같은 보안상 중요한 파일이 있다면, 개별적으로 생성해주어야한다.

- Dockerfile이 존재하는 폴더 위치에서 실행

docker build -t ozofweird/spring:0.0 .

Spring 프로젝트 빌드는 성공하였으나, 'System has not been booted with systemd as init system (PID 1). Can't operate.' 문제를 해결하지 못했습니다. CentOS가 아닌 Ubuntu로 환경을 구축했을 때에는 아무런 이상없이 동작함을 확인할 수 있었습니다. CentOS, Nginx, 등 시간이 더 필요해보입니다. 위의 방법으로 해결하신 분이 계시다면 댓글 부탁드립니다.ㅠ


아래의 참고 링크는 다른 블로그의 Spring 프로젝트 도커 환경 구축 방법입니다.

 

[참고] daddyprogrammer.org/post/12542/springboot-docker-integration/

[참고] swipa.dev/43

[참고] inma.tistory.com/148

728x90