웹사이트 검색

Ubuntu 20.04 LTS에서 Dockerfile로 Docker 이미지를 생성하는 방법


이 튜토리얼은 다음 OS 버전에 대해 존재합니다.

  • 우분투 16.04(Xenial Xerus)

이 페이지에서

  1. Dockerfile 명령 소개
  2. 1단계 - Ubuntu 20.04에 Docker 설치
  3. 2단계 - Dockerfile 및 기타 구성 만들기
  4. 3단계 - 새 사용자 지정 빌드 및 새 컨테이너 실행\n
  5. 4단계 - 테스트

Docker는 주로 개발자와 시스템 관리자를 위한 운영 체제 수준의 가상화입니다. Docker를 사용하면 격리된 환경에서 애플리케이션을 더 쉽게 만들고 배포할 수 있습니다.

Dockerfile은 새 도커 이미지를 빌드하기 위해 도커 환경에서 순차적으로 자동 실행되는 명령 및 지침 모음이 포함된 스크립트입니다.

이 자습서에서는 Dockerfile을 사용하여 고유한 Docker 이미지를 만드는 방법을 보여줍니다. 자체 Docker 이미지를 빌드할 수 있도록 Dockerfile과 관련된 세부 정보를 설명합니다.

전제 조건

이 가이드에서는 1GB RAM, 25GB 여유 디스크 공간 및 2개의 CPU가 있는 Ubuntu 20.04를 사용합니다. 또한 Ubuntu 20.04를 기본 이미지로 사용하여 사용자 지정 Docker 이미지를 빌드합니다.

Dockerfile 명령 소개

Dockerfile은 Docker 이미지를 빌드하기 위한 모든 명령이 포함된 스크립트입니다. Dockerfile에는 docker build 명령으로 Docker 이미지를 만드는 데 사용되는 모든 지침이 포함되어 있습니다.

첫 번째 Dockerfile을 만들기 전에 Dockerfile 지침을 숙지해야 합니다. 알아야 할 몇 가지 Dockerfile 명령 아래.

에서

만들려는 새 이미지의 기본 이미지를 설정합니다. FROM 명령은 새 빌드 단계를 초기화하며 Dockerfile의 맨 위에 있어야 합니다.

상표

이 명령을 사용하면 버전, 설명, 관리자 등과 같은 Docker 이미지에 대한 추가 정보를 추가할 수 있습니다. LABEL 명령은 여러 레이블과 여러 줄 값을 추가할 수 있는 키-값 쌍입니다.

운영

이 명령은 도커 이미지의 빌드 프로세스 중에 명령을 실행하는 데 사용됩니다. Docker 이미지에 필요한 추가 패키지를 설치할 수 있습니다.

추가하다

ADD 명령은 파일, 디렉터리 또는 원격 파일을 URL에서 Docker 이미지로, src에서 절대 경로 dest로 복사하는 데 사용됩니다. 또한 파일의 기본 소유권을 설정할 수 있습니다.

ENV

ENV 명령어는 빌드 단계에서 사용할 수 있고 인라인으로 대체할 수 있는 환경 변수를 정의하는 데 사용됩니다.

CMD

CMD 명령은 컨테이너를 실행할 때 실행할 기본 명령을 정의하는 데 사용됩니다. 그리고 Dockerfile은 하나의 CMD 명령어만 포함해야 하며 여러 CMD가 있는 경우 마지막 CMD 명령어가 실행됩니다.

폭로하다

이 명령은 런타임에 특정 네트워크 포트의 컨테이너 포트를 노출하는 데 사용됩니다. 노출되는 기본 프로토콜은 TCP이지만 TCP 또는 UDP를 지정할 수 있습니다.

아르그

ARG 명령은 사용자가 빌드 타임에 전달할 수 있는 변수를 정의하는 데 사용됩니다. --build-arg variable=value 옵션을 사용하여 빌드 시간 동안 docker build 명령에서 이 명령을 사용할 수 있으며 Dockerfile을 통해 전달할 수 있습니다. 또한 Dockerfile에서 여러 ARG를 사용할 수 있습니다.

진입 지점

ENTRYPOINT 명령은 컨테이너가 실행 중일 때 실행될 첫 번째 및 기본 명령을 정의하는 데 사용됩니다. ENTRYPOINT 명령으로 애플리케이션을 시작하는 명령을 정의하십시오.

WORKDIR

WORKDIR 명령은 Docker 이미지의 기본 작업 디렉터리를 정의하는 데 사용됩니다. RUN, CMD, ENTRYPOINT 및 ADD 명령어는 WORKDIR 명령어를 따릅니다. Dockerfile에 WORKDIR 명령을 여러 개 추가할 수 있으며, 없는 경우 자동으로 생성됩니다.

사용자

USER 명령은 이미지를 실행할 때 기본 사용자 또는 gid를 정의하는 데 사용됩니다. RUN, CMD 및 ENTRYPOINT는 Dockerfile의 USER 명령을 따릅니다.

용량

컨테이너와 호스트 시스템 간의 액세스/링크된 디렉터리를 활성화하는 데 사용되는 VOLUME 명령 광고.

이제 첫 번째 Dockerfile 생성을 시작하겠습니다.

1단계 - Ubuntu 20.04에 Docker 설치

Dockerfile을 만들기 전에 Ubuntu FocalFossa 리포지토리에서 기본적으로 사용할 수 있는 Ubuntu 20.04 시스템에 Docker를 설치합니다.

Ubuntu 리포지토리의 모든 패키지 목록을 업데이트하고 아래의 apt 명령을 사용하여 Docker를 설치합니다.

sudo apt update
sudo apt install docker.io

모든 설치가 완료되면 Docker 서비스를 시작하고 시스템 부팅에 추가하십시오.

systemctl start docker
systemctl enable docker

이제 아래 명령을 사용하여 Docker 서비스를 확인하십시오.

systemctl status docker

Docker 서비스는 Ubuntu 20.04에서 실행 중입니다.

다음으로 아래의 docker 명령을 실행하여 설치가 올바른지 확인합니다.

docker run hello-world

아래는 당신이 얻을 결과입니다.

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

알 수 있듯이 Docker에서 Hello World 메시지를 받고 Ubuntu 20.04에서 Docker 설치가 성공적으로 완료되었습니다.

2단계 - Dockerfile 및 기타 구성 만들기

이 단계에서는 Dockerfile을 사용하여 애플리케이션에 대한 사용자 지정 Docker 이미지를 빌드하는 방법을 보여줍니다. PHP-FPM 및 Nginx 서비스를 위해 Ubuntu 20.04 이미지를 기반으로 새로운 사용자 지정 Docker 이미지를 만든 다음 간단한 phpinfo 스크립트로 새 컨테이너를 실행합니다.

먼저 새 프로젝트 디렉터리를 만들고 빈 Dockerfile을 만듭니다.

mkdir -p nginx-image; cd nginx-image/
touch Dockerfile

이제 자체 편집기를 사용하여 Dockerfile 스크립트를 편집합니다(이 예제에서는 vim을 사용함).

vim Dockerfile

줄 맨 위에 아래와 같이 FROM 명령어를 사용하여 기본 이미지 Ubuntu 20.04 이미지를 추가합니다.

#Download base image ubuntu 20.04
FROM ubuntu:20.04

이제 LABEL 명령을 사용하여 사용자 정의 이미지에 대한 자세한 정보를 추가하십시오.

# LABEL about the custom image
LABEL maintainer=""
LABEL version="0.1"
LABEL description="This is custom Docker Image for \
the PHP-FPM and Nginx Services."

apt 패키지 설치의 경우 환경 변수 DEBIAN_FRONTEND=noninteractive를 사용하여 대화형 설치 후 단계를 건너뜁니다.

# Disable Prompt During Packages Installation
ARG DEBIAN_FRONTEND=noninteractive

그런 다음 패키지를 설치하기 전에 apt update 명령을 실행하십시오.

# Update Ubuntu Software repository
RUN apt update

이제 Nginx, PHP-FPM 및 감독자 패키지를 설치합니다. 모든 설치가 완료되면 모든 패키지 캐시를 제거하여 사용자 지정 이미지의 크기를 줄입니다.

# Install nginx, php-fpm and supervisord from ubuntu repository
RUN apt install -y nginx php-fpm supervisor && \
    rm -rf /var/lib/apt/lists/* && \
    apt clean

사용자 지정 이미지에 전달할 수 있는 새 환경 변수를 정의합니다.

#Define the ENV variable
ENV nginx_vhost /etc/nginx/sites-available/default
ENV php_conf /etc/php/7.4/fpm/php.ini
ENV nginx_conf /etc/nginx/nginx.conf
ENV supervisor_conf /etc/supervisor/supervisord.conf

이제 Nginx 기본 구성을 nginx_vhost 변수에 복사하고 php.ini 구성 파일에서 PHP 구성 cgi.fix_pathinfo=1을 cgi.fix_pathinfo=0으로 바꾼 다음 데몬 끄기 옵션을 기본 nginx_conf 변수에 추가합니다.

# Enable PHP-fpm on nginx virtualhost configuration
COPY default ${nginx_vhost}
RUN sed -i -e 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' ${php_conf} && \
    echo "\ndaemon off;" >> ${nginx_conf}

사용자 지정 Supervisord 구성을 Supervisor_conf 변수에 복사합니다.

#Copy supervisor configuration
COPY supervisord.conf ${supervisor_conf}

PHP-FPM 양말 파일을 위한 새 디렉토리를 생성하고 웹 루트 디렉토리 /var/www/html 및 PHP-FPM 디렉토리 /run/php의 소유권을 기본 사용자 www-data로 변경합니다.

RUN mkdir -p /run/php && \
    chown -R www-data:www-data /var/www/html && \
    chown -R www-data:www-data /run/php

모든 디렉터리를 호스트 시스템에 탑재할 수 있도록 사용자 지정 이미지의 볼륨을 정의합니다.

# Volume configuration
VOLUME ["/etc/nginx/sites-enabled", "/etc/nginx/certs", "/etc/nginx/conf.d", "/var/log/nginx", "/var/www/html"]

이제 start.sh 스크립트를 추가하고 아래와 같이 CMD 명령을 사용하여 기본 컨테이너 명령을 정의합니다.

# Copy start.sh script and define default command for the container
COPY start.sh /start.sh
CMD ["./start.sh"]

마지막으로 EXPOSE 명령을 사용하여 컨테이너의 기본 HTTP 및 HTTPS 포트를 엽니다.

# Expose Port for the Application 
EXPOSE 80 443

저장하고 닫습니다.

아래는 방금 생성한 전체 Dockerfile 스크립트입니다.

# Download base image ubuntu 20.04
FROM ubuntu:20.04

# LABEL about the custom image
LABEL maintainer=""
LABEL version="0.1"
LABEL description="This is custom Docker Image for \
the PHP-FPM and Nginx Services."

# Disable Prompt During Packages Installation
ARG DEBIAN_FRONTEND=noninteractive

# Update Ubuntu Software repository
RUN apt update

# Install nginx, php-fpm and supervisord from ubuntu repository
RUN apt install -y nginx php-fpm supervisor && \
    rm -rf /var/lib/apt/lists/* && \
    apt clean
    
# Define the ENV variable
ENV nginx_vhost /etc/nginx/sites-available/default
ENV php_conf /etc/php/7.4/fpm/php.ini
ENV nginx_conf /etc/nginx/nginx.conf
ENV supervisor_conf /etc/supervisor/supervisord.conf

# Enable PHP-fpm on nginx virtualhost configuration
COPY default ${nginx_vhost}
RUN sed -i -e 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' ${php_conf} && \
    echo "\ndaemon off;" >> ${nginx_conf}
    
# Copy supervisor configuration
COPY supervisord.conf ${supervisor_conf}

RUN mkdir -p /run/php && \
    chown -R www-data:www-data /var/www/html && \
    chown -R www-data:www-data /run/php
    
# Volume configuration
VOLUME ["/etc/nginx/sites-enabled", "/etc/nginx/certs", "/etc/nginx/conf.d", "/var/log/nginx", "/var/www/html"]

# Copy start.sh script and define default command for the container
COPY start.sh /start.sh
CMD ["./start.sh"]

# Expose Port for the Application
EXPOSE 80 443

다음으로 Nginx, Supervisord 및 start.sh 스크립트에 대한 새로운 추가 구성을 생성합니다.

기본 Nginx 가상 호스트 구성에는 PHP-FPM 섹션이 포함됩니다. 실제로 변경 없이 사용자 지정 이미지를 사용하여 PHP 스크립트를 실행할 수 있습니다.

편집기를 사용하여 새 Nginx 기본 가상 호스트 구성을 만듭니다.

vim default

다음 구성을 붙여넣습니다.

server {
    listen 80 default_server;
 
    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;
 
    server_name _;
 
    location / {
        try_files $uri $uri/ =404;
    }
 
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
       fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }
}

저장하고 닫습니다.

다음으로 자동으로 실행될 Nginx 및 PHP-FPM 프로그램을 모두 포함하는 supervisrod.conf 구성을 생성합니다.

편집기를 사용하여 supervisrod.conf 파일을 만듭니다.

vim supervisord.conf

다음 구성을 붙여넣습니다.

[unix_http_server]
file=/dev/shm/supervisor.sock   ; (the path to the socket file)
 
[supervisord]
logfile=/var/log/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB        ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10           ; (num of main logfile rotation backups;default 10)
loglevel=info                ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false               ; (start in foreground if true;default false)
minfds=1024                  ; (min. avail startup file descriptors;default 1024)
minprocs=200                 ; (min. avail process descriptors;default 200)
user=root             ;

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
 
[supervisorctl]
serverurl=unix:///dev/shm/supervisor.sock ; use a unix:// URL  for a unix socket
 
[include]
files = /etc/supervisor/conf.d/*.conf
 
[program:php-fpm7.4]
command=/usr/sbin/php-fpm7.4 -F
numprocs=1
autostart=true
autorestart=true
 
[program:nginx]
command=/usr/sbin/nginx
numprocs=1
autostart=true
autorestart=true

저장하고 닫습니다.

이제 t=your editor를 사용하여 start.sh 스크립트를 생성하십시오. 시작하기 위한 Supervisord 명령이 포함됩니다.

vim start.sh

다음 구성을 붙여넣습니다.

#!/bin/sh
/usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf

저장하고 닫습니다.

start.sh 스크립트를 실행 가능하게 만드십시오.

chmod +x start.sh

결과적으로 맞춤형 Docker 이미지에 대한 모든 구성이 생성되었으며 아래는 우리가 생성한 모든 구성입니다.

tree .

이제 이러한 구성을 기반으로 새로운 사용자 지정 이미지를 만들 준비가 되었습니다.

3단계 - 새 사용자 지정 빌드 및 새 컨테이너 실행

Docker 사용자 지정 이미지를 생성하려면 프로젝트 디렉터리 nginx-image로 이동하여 아래와 같이 docker build 명령을 실행합니다.

docker build -t nginx-image .

이 명령은 기본 이미지 Ubuntu 20.04를 다운로드하고 이름이 nginx-image인 새 사용자 지정 이미지를 만듭니다.

모든 프로세스가 완료되면 다음 명령을 사용하여 시스템에서 사용 가능한 Docker 이미지 목록을 확인하십시오.

docker image ls

아래는 당신이 얻을 결과입니다.

볼 수 있듯이 새로운 사용자 정의 Docker 이미지 nginx-image가 생성되었습니다.

다음으로 nginx-image를 기반으로 새로운 Docker 컨테이너를 실행합니다.

로컬 컴퓨터에서 모든 웹 파일을 저장하는 데 사용할 webroot라는 새 디렉터리를 만듭니다.

mkdir -p /webroot

이제 아래의 docker run 명령을 사용하여 test-container라는 새 컨테이너를 만듭니다.

docker run -d -v /webroot:/var/www/html -p 8080:80 --name test-container nginx-image

메모:

  • --name test-container nginx-image=docker 이미지 nginx-image를 기반으로 test-container라는 이름으로 새 컨테이너를 만듭니다.
  • -p 8080:80 = 호스트 시스템의 포트 8080에서 실행되는 테스트 컨테이너 컨테이너.\n
  • -v /webroot:/var/www/html = 호스트 시스템의 /webroot 디렉터리를 컨테이너의 /var/www/html 디렉터리에 다시 씁니다.\n

그런 다음 다음 명령을 사용하여 시스템에서 실행 중인 모든 컨테이너를 확인합니다.

docker ps

아래는 당신이 얻을 결과입니다.

결과적으로 nginx-image를 기반으로 하고 포트 8080을 노출하는 test-container라는 새 컨테이너가 실행됩니다.

4단계 - 테스트

컨테이너가 올바르게 실행되는지 확인하기 위해 호스트 시스템의 /webroot 루트 디렉토리에 새로운 index.html 및 phpinfo 파일을 생성합니다. /webroot 디렉토리가 컨테이너 디렉토리 /var/www/html에 마운트되기 때문입니다.

다음 명령을 사용하여 /webroot 디렉터리에 index.html 파일을 만듭니다.

echo '<h1>Nginx and PHP-FPM 7.4 inside Docker Container with Ubuntu 20.04 Base Image</h1>' > /webroot/index.html

이제 포트 8080에서 curl 명령을 사용하여 컨테이너 액세스를 테스트합니다.

curl server-ip:8080
curl -I server-ip:8080

결과적으로 방금 생성한 기본 index.html 페이지를 얻게 됩니다.

다음으로 /webroot 디렉터리에 새 PHP 파일 info.php를 생성하여 PHP-FPM 서비스가 실행 중인지 확인합니다.

다음 명령을 사용하여 info.php 파일을 생성합니다.

echo '<?php phpinfo(); ?>' > /webroot/info.php

다음으로, 웹 브라우저를 열고 info.php 파일의 경로 뒤에 포트 8080이 있는 서버 IP 주소를 입력합니다.

이제 아래와 같이 phpinfo 페이지가 나타납니다.

볼 수 있듯이 테스트 컨테이너는 성공적으로 PHP 스크립트를 로드합니다.

그 결과 새로운 맞춤형 Docker 이미지를 성공적으로 생성하고 이를 기반으로 새 컨테이너를 오류 없이 실행했습니다.