본문 바로가기
IT

우분투 nginx 서버 Docker 설치 및 이미지 만들기

by geddy 2024. 1. 23.

이 글에서는 Docker 이미지 만드는 법에 대해서 설명합니다. 

우분투 nginx 서버 Docker 설치 및 이미지 만들기 썸네일

  • Docker로 운영중인 nginx우분투 서버 이미지로 만들기 절차
  • 실행 과정
 

운영중인 nginx우분투 서버 Docker 이미지 만들기 절차


Docker를 사용해서 현재 운영중인 nginx 와 flask 앱을 실행중인 우분투 서버를 docker 이미지로 만들려고 합니다.

아래의 순서를 따라서 이미지 생성을 진행합니다.

Docker를 사용하여 우분투 서버 환경을 일관되게 관리하려면 다음 단계를 수행해야 합니다.

1. Docker 설치

우분투 서버에서 Docker를 다운로드 및 설치합니다.

bash
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get install docker-ce

2. Dockerfile 작성

애플리케이션 루트 디렉토리에서 'Dockerfile'이라는 파일을 생성합니다. 이 파일은 우분투 서버 환경을 구축하기 위한 지침을 제공합니다.

 
FROM ubuntu:20.04

# 필요한 패키지 및 의존성 설치
RUN apt-get update && apt-get install -y \
    <your_required_packages> \
    && rm -rf /var/lib/apt/lists/*

# 사용자 정의 스크립트 추가 (옵션)
ADD your_script.sh /usr/local/bin/

# 작업 디렉토리 설정
WORKDIR /app

# 포트 정보 설정 (옵션)
EXPOSE <port_number>

# 컨테이너 실행 시 수행될 명령
CMD ["your_script.sh"]

3. Docker 이미지 만들기

Dockerfile이 위치한 애플리케이션 디렉토리에서 다음 명령어를 실행하여 이미지를 빌드합니다.

bash
docker build -t <your_image_name> .

4. Docker 컨테이너 실행

빌드한 이미지를 사용하여 컨테이너를 실행합니다.

bash
docker run -d -p <host_port>:<container_port> --name <your_container_name> <your_image_name>

이제 멈추거나 삭제한 후 다시 실행할 때마다 동일한 환경이 있는 Docker 컨테이너가 실행됩니다. dictionaryWith 문서를 작성 개발 환경 또는 프로덕션 환경과 동일한 최상의 유용한 종속성 상태로 도커 서버 코드 파일과 다른 파일 정보를 추가할 수 있습니다.

 

코드 파일 및 환경을 업데이트할 때마다 Dockerfile 및 빌드를 사용하여 이미지를 다시 빌드하여 일관된 컨테이너 환경을 유지해야 합니다.


실행 과정


위의 절차대로 하나씩 실행해서 확인해보도록 하겠습니다. 

1.   Docker 설치

eddy_lee@instance-1:~$ sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
Reading package lists... Done
Building dependency tree
Reading state information... Done
ca-certificates is already the newest version (20230311ubuntu0.20.04.1).
ca-certificates set to manually installed.
curl is already the newest version (7.68.0-1ubuntu2.19).
curl set to manually installed.
software-properties-common is already the newest version (0.99.9.11).
software-properties-common set to manually installed.
The following packages were automatically installed and are no longer required:
  libatasmart4 libblockdev-fs2 libblockdev-loop2 libblockdev-part-err2 libblockdev-part2 libblockdev-swap2 libblockdev-utils2 libblockdev2 libmbim-glib4 libmbim-proxy
  libmm-glib0 libnspr4 libnss3 libnuma1 libparted-fs-resize0 libqmi-glib5 libqmi-proxy libudisks2-0 libxmlb2 usb-modeswitch usb-modeswitch-data
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
  apt-transport-https
0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.
Need to get 1704 B of archives.
After this operation, 162 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://asia-northeast3.gce.archive.ubuntu.com/ubuntu focal-updates/universe amd64 apt-transport-https all 2.0.9 [1704 B]
Fetched 1704 B in 0s (21.1 kB/s)
Selecting previously unselected package apt-transport-https.
(Reading database ... 69629 files and directories currently installed.)
Preparing to unpack .../apt-transport-https_2.0.9_all.deb ...
Unpacking apt-transport-https (2.0.9) ...
Setting up apt-transport-https (2.0.9) ...
eddy_lee@instance-1:~$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
OK
eddy_lee@instance-1:~$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
Get:1 https://download.docker.com/linux/ubuntu focal InRelease [57.7 kB]
Hit:2 http://asia-northeast3.gce.archive.ubuntu.com/ubuntu focal InRelease
Hit:3 http://asia-northeast3.gce.archive.ubuntu.com/ubuntu focal-updates InRelease
Hit:4 http://asia-northeast3.gce.archive.ubuntu.com/ubuntu focal-backports InRelease
Get:5 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages [32.5 kB]
Get:6 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]
Fetched 204 kB in 1s (196 kB/s)
Reading package lists... Done
eddy_lee@instance-1:~$ sudo apt-get install docker-ce
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libatasmart4 libblockdev-fs2 libblockdev-loop2 libblockdev-part-err2 libblockdev-part2 libblockdev-swap2 libblockdev-utils2 libblockdev2 libmbim-glib4 libmbim-proxy
  libmm-glib0 libnspr4 libnss3 libnuma1 libparted-fs-resize0 libqmi-glib5 libqmi-proxy libudisks2-0 libxmlb2 usb-modeswitch usb-modeswitch-data
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  containerd.io docker-buildx-plugin docker-ce-cli docker-ce-rootless-extras docker-compose-plugin pigz slirp4netns
Suggested packages:
  aufs-tools cgroupfs-mount | cgroup-lite
The following NEW packages will be installed:
  containerd.io docker-buildx-plugin docker-ce docker-ce-cli docker-ce-rootless-extras docker-compose-plugin pigz slirp4netns
0 upgraded, 8 newly installed, 0 to remove and 0 not upgraded.
Need to get 114 MB of archives.
After this operation, 414 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://asia-northeast3.gce.archive.ubuntu.com/ubuntu focal/universe amd64 pigz amd64 2.4-1 [57.4 kB]
Get:2 https://download.docker.com/linux/ubuntu focal/stable amd64 containerd.io amd64 1.6.22-1 [28.3 MB]
Get:3 http://asia-northeast3.gce.archive.ubuntu.com/ubuntu focal/universe amd64 slirp4netns amd64 0.4.3-1 [74.3 kB]
Get:4 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-buildx-plugin amd64 0.11.2-1~ubuntu.20.04~focal [28.2 MB]
Get:5 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce-cli amd64 5:24.0.5-1~ubuntu.20.04~focal [13.3 MB]
Get:6 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce amd64 5:24.0.5-1~ubuntu.20.04~focal [22.9 MB]
Get:7 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce-rootless-extras amd64 5:24.0.5-1~ubuntu.20.04~focal [9032 kB]
Get:8 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-compose-plugin amd64 2.20.2-1~ubuntu.20.04~focal [11.9 MB]
Fetched 114 MB in 2s (66.4 MB/s)
Selecting previously unselected package pigz.
(Reading database ... 69633 files and directories currently installed.)
Preparing to unpack .../0-pigz_2.4-1_amd64.deb ...
Unpacking pigz (2.4-1) ...
Selecting previously unselected package containerd.io.
Preparing to unpack .../1-containerd.io_1.6.22-1_amd64.deb ...
Unpacking containerd.io (1.6.22-1) ...
Selecting previously unselected package docker-buildx-plugin.
Preparing to unpack .../2-docker-buildx-plugin_0.11.2-1~ubuntu.20.04~focal_amd64.deb ...
Unpacking docker-buildx-plugin (0.11.2-1~ubuntu.20.04~focal) ...
Selecting previously unselected package docker-ce-cli.
Preparing to unpack .../3-docker-ce-cli_5%3a24.0.5-1~ubuntu.20.04~focal_amd64.deb ...
Unpacking docker-ce-cli (5:24.0.5-1~ubuntu.20.04~focal) ...
Selecting previously unselected package docker-ce.
Preparing to unpack .../4-docker-ce_5%3a24.0.5-1~ubuntu.20.04~focal_amd64.deb ...
Unpacking docker-ce (5:24.0.5-1~ubuntu.20.04~focal) ...
Selecting previously unselected package docker-ce-rootless-extras.
Preparing to unpack .../5-docker-ce-rootless-extras_5%3a24.0.5-1~ubuntu.20.04~focal_amd64.deb ...
Unpacking docker-ce-rootless-extras (5:24.0.5-1~ubuntu.20.04~focal) ...
Selecting previously unselected package docker-compose-plugin.
Preparing to unpack .../6-docker-compose-plugin_2.20.2-1~ubuntu.20.04~focal_amd64.deb ...
Unpacking docker-compose-plugin (2.20.2-1~ubuntu.20.04~focal) ...
Selecting previously unselected package slirp4netns.
Preparing to unpack .../7-slirp4netns_0.4.3-1_amd64.deb ...
Unpacking slirp4netns (0.4.3-1) ...
Setting up slirp4netns (0.4.3-1) ...
Setting up docker-buildx-plugin (0.11.2-1~ubuntu.20.04~focal) ...
Setting up containerd.io (1.6.22-1) ...
Created symlink /etc/systemd/system/multi-user.target.wants/containerd.service → /lib/systemd/system/containerd.service.
Setting up docker-compose-plugin (2.20.2-1~ubuntu.20.04~focal) ...
Setting up docker-ce-cli (5:24.0.5-1~ubuntu.20.04~focal) ...
Setting up pigz (2.4-1) ...
Setting up docker-ce-rootless-extras (5:24.0.5-1~ubuntu.20.04~focal) ...
Setting up docker-ce (5:24.0.5-1~ubuntu.20.04~focal) ...
Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /lib/systemd/system/docker.service.
Created symlink /etc/systemd/system/sockets.target.wants/docker.socket → /lib/systemd/system/docker.socket.
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for systemd (245.4-4ubuntu3.22) ...


2. Dockerfile 작성

이걸 하려고 하니, 두 번째 "# 필요한 패키지 및 의존성 설치"를 작성해야합니다. 그런데 내가 설치한 패키지가 뭔지 모르겠습니다. 

dpkg -l 명령은 시스템에 설치된 모든 패키지를 나열합니다. 이 명령만으로는 기존에 설치된 패키지와 사용자가 설치한 패키지를 구분할 수 없습니다. 하지만, /var/log/apt/history.log 파일을 참조하여 패키지 설치, 업데이트 및 제거 이력을 확인할 수 있습니다.

다음의 내용을 참고하여 지금까지 설치한 내역을 찾아냅니다.

  1. APT 패키지 관리자 이력 확인 /var/log/apt/history.log 파일에 패키지 관리자를 통해 설치된 패키지의 이력이 저장됩니다. 이 파일에서 InstallUpgrade 항목을 찾아 사용자가 설치한 패키지를 확인해보세요.
  2. 커스텀 스크립트 이용 아래의 커스텀 쉘 스크립트를 사용하면 사용자가 설치한 패키지 목록을 생성할 수 있습니다.
bash
#!/bin/bash
log_files=($(ls /var/log/apt/history.log*))

for log in "${log_files[@]}"
do
  if [[ "$log" == *".gz" ]]; then
    zgrep -P 'Commandline: apt(-get)? install' $log | grep -oP '(?<=install).+' | tr ' ' '\n' | sort
  else
    grep -P 'Commandline: apt(-get)? install' $log | grep -oP '(?<=install).+' | tr ' ' '\n' | sort
  fi
done

위 스크립트는 ls를 사용하여 /var/log/apt/history.log* 파일을 찾고, APT 커맨드에서 패키지 설치 이력을 추출합니다. 스크립트를 실행하면 사용자가 설치한 패키지 목록이 출력됩니다.


위의 스크립트를 돌려보면 다음과 같이 나타납니다. 

아래 패키지에서 내 앱을 실행하는데 필요한 것들만 골라서 Dockerfile에 추가합니다. 

eddy_lee@instance-1:~$ bash pkg.sh
--assume-yes
-qqy
-y
apt-transport-https
ca-certificates
certbot
curl
docker-ce
grub-pc
libgl1-mesa-glx
linux-gcp
net-tools
nginx
python3-certbot-nginx
python3-pip
python3-venv
shim-signed
software-properties-common
unzip

아래는 수정된 Dockerfile입니다.

 

Dockerfile
# 기본 이미지 설정
FROM ubuntu:20.04

# 패키지 업데이트 및 필요한 패키지 설치
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    python3 \
    python3-pip \
    python3-venv \
python3-certbot-nginx \
 nginx \  ca-certificates \  curl \  unzip \  apt-transport-https \  libgl1-mesa-glx \  && rm -rf /var/lib/apt/lists/*  # 파이썬 패키지 설치 COPY requirements.txt /app/ RUN pip3 install --no-cache-dir -r /app/requirements.txt  # Nginx 설정 파일 복사 COPY nginx.conf /etc/nginx/sites-available/default  # Flask 앱 복사 COPY app /app  # 실행 스크립트 추가 COPY start.sh /usr/local/bin/  # 권한 설정 RUN chmod +x /usr/local/bin/start.sh  # 작업 디렉토리 설정 WORKDIR /app  # 포트 정보 설정 EXPOSE 80  # 컨테이너 실행 시 수행될 명령 CMD ["start.sh"]

위의 내용 중 패키지 설치 부분만 자세히 살펴보면 다음과 같습니다. 

 

RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    python3 \
    python3-pip \
    python3-venv \
python3-certbot-nginx \
    nginx \
    ca-certificates \
    curl \
    unzip \
    apt-transport-https \
    libgl1-mesa-glx \
    && rm -rf /var/lib/apt/lists/*
  1. apt-get update: 패키지 목록을 업데이트합니다.
  2. DEBIAN_FRONTEND=noninteractive: 패키지 설치 중 사용자 입력을 요구하지 않도록 합니다.
  3. apt-get install -y --no-install-recommends: 다음과 같은 패키지를 설치합니다.
    • python3: Python 3 인터프리터
    • python3-pip: Python 3용 pip 패키지 매니저
    • python3-venv: Python 3 가상 환경 관리 도구
    • python3-certbot-nginx: Nginx를 위한 Certbot (Let's Encrypt SSL 인증서 관리)
    • nginx: 웹 서버로 사용되는 Nginx
    • ca-certificates: 일반적인 인증서 파일
    • curl: 명령 줄에서 URL과 상호작용할 수 있는 도구
    • unzip: 파일 압축 해제 도구
    • apt-transport-https: HTTPS를 통해 패키지를 다운로드할 수 있는 도구
    • libgl1-mesa-glx: OpenGL 라이브러리 및 실행 파일
  4. 마지막으로 && rm -rf /var/lib/apt/lists/*: 패키지 설치 후 불필요한 파일을 삭제하여 이미지 크기를 줄입니다.

 

 

# 기본 이미지 설정

FROM ubuntu:20.04
 
# 패키지 업데이트 및 필요한 패키지 설치
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    python3 \
    python3-pip \
    python3-venv \
    python3-certbot-nginx \
    nginx \
    ca-certificates \
    curl \
    unzip \
    apt-transport-https \
    libgl1-mesa-glx \
    && rm -rf /var/lib/apt/lists/*
 
# 설치된 파이썬 패키지와 flask 앱 복사
COPY venv 
COPY flask  imgFilterApp 
 
# Nginx 설정 파일 복사
COPY nginx.conf /etc/nginx/sites-available/default
COPY nginx.conf /etc/nginx/nginx.conf
COPY myflaskapp /etc/nginx/sites-available/myflaskapp
# Flask 앱 복사
COPY app /app
 
# 실행 스크립트 추가
COPY start.sh /usr/local/bin/
 
# 권한 설정
RUN chmod +x /usr/local/bin/start.sh
 
# 작업 디렉토리 설정
WORKDIR /app
 
# 포트 정보 설정
EXPOSE 80, 443
 
# 컨테이너 실행 시 수행될 명령
CMD ["start.sh"]
 
docker 실행시 entrypoint가 멈추면 컨테이너가 종료된다. 그러므로, 아래와 같이 루프를 도는 loop.sh을 만들어서 entrypoint로 실행한다. 
 
(venv) ubuntu@instance-20230803-1044:~$ cat > loop.sh
#!/bin/bash

INTERVAL=$1

while true;
do
  ps x;
  sleep $INTERVAL;
done
 

3. docker build

docker file을 만들었으면 아래 명령어와 같이 build를 합니다. 
 
PS C:\Users> docker build -t xxxx:1.3 ./
[+] Building 0.5s (15/15) FINISHED
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 792B 0.1s
.....
=> exporting to image 0.1s
=> => exporting layers 0.1s
=> => writing image sha256:972b8dd43173941863fae7ec40d24ec5006222b3ad89aad3566b829917e93245 0.0s
=> => naming to docker.io/library/xxxx:1.0 0.0s
 

4. docker hub에 push

docker hub에 push를 합니다. 
docker tag xxxx:1.3 계정/이름:1.3
 
docker push 계정/이름:1.3
facebook twitter kakaoTalk kakaostory naver band shareLink