DEV/Docker-Debian

1. Ubuntu 22.04 에서 Docker 구성 (APM 기본 설치)

서버엔지니어 2023. 3. 1.
728x90

1. APT 패키지 업데이트 및 설치 및 호스트명 변경

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

업그레이드 할때 현버전 유지해도되고 Y해서 업그레이드해도 됩니다.

apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release

vi /etc/hostname

===============================================================================

Ubuntu-Docker

===============================================================================

hostnamectl hostname --static Ubuntu-Docker

init 6

 

2. Docker 공식 GPG 설치

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

 

3. 저장소 설정

echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu  $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

 

4. Docker 설치 및 확인

apt-get -y update
apt-get -y install docker-ce docker-ce-cli containerd.io
docker --version

 

5. Compose 설치 및 확인

Docker Compose는 여러개의 도커 어플리케이션 컨테이너들을 정의하고 실행 할 수 있게 도와주는 툴 입니다.
도커 컨테이너 구동 명령시 옵션으로 환경 값을 줄 수 있는데, 이경우 명령 라인이 길어지는 불편함이 있습니다.
docker-compose 는 이런 불편함을 없애고, 미리 준비한 환경을 파일(.yml) 을 사용하며 여러 컨테이너를 한 번에 관리할 수 있습니다.
YAML 파일을 사용해 어플리케이션의 서비스를 설정하고 하나의 커맨드만으로 여러개의 도커 컨테이너들을 사용 할 수 있습니다. Docker 를 설치 해도 Compose 가 딸려 오는 것은 아니기 때문에 따로 설치 해 주어야 합니다. 이전에는 stand-alone 으로만 제공되었지만 이제는 플러그인 형태로 지원되고 있습니다.

 

1) Plugin 형태로 사용할 경우 (매뉴얼 진행 형태) / 현재 방식
apt -y install docker-compose-plugin
docker compose version


2) Standalone 형태로 사용할 경우 / 예전 방식
curl -SL https://github.com/docker/compose/releases/download/v2.12.2/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
docker-compose --version // 설치 여부 확인

 

6. Docker 실전

[ Docker 삭제 ]
1. Docker 관련 패키지를 제거
apt purge docker-ce docker-ce-cli containerd.io

2. 호스트의 이미지, 컨테이너, 볼륨 또는 사용자 지정 구성파일 제거 (모든 이미지, 컨테이너 및 볼륨 수동 삭제)
rm -rf /var/lib/docker
rm -rf /var/lib/containerd

 

[ APM 설치 ]
1. 설치 및 확인
특정 버전을 명시하지 않으면 최신 버전의 이미지가 다운로드 됩니다.
사용 예) docker pull {이미지}:{버전}
docker pull httpd:2.4.54
docker pull php:8.2.0-fpm
docker pull mysql:8.0.31

다운로드 된 이미지 리스트를 출력합니다.
docker images

===============================================================================

REPOSITORY   TAG                 IMAGE ID       CREATED          SIZE
phpmyadmin   latest              b2c631705a0e   13 days ago      517MB
httpd        2.4.54              463980270363   7 weeks ago      145MB
php          8.2.0-fpm           8ee3a55f199a   2 months ago     450MB
mysql        8.0.31              7484689f290f   2 months ago     538MB

===============================================================================

 

! 잠깐

 

Apache httpd 2.4 default layout

===============================================================================

ServerRoot              ::      /usr/local/apache2
DocumentRoot            ::      /usr/local/apache2/htdocs
Apache Config File      ::      /usr/local/apache2/conf/httpd.conf
Other Config Files      ::      /usr/local/apache2/conf/extra/
SSL Config File         ::      /usr/local/apache2/conf/extra/httpd-ssl.conf
ErrorLog                ::      /usr/local/apache2/logs/error_log
AccessLog               ::      /usr/local/apache2/logs/access_log
cgi-bin                 ::      /usr/local/apache2/cgi-bin (enabled by default, but some of the bundled scripts are 644)
binaries (apachectl)    ::      /usr/local/apache2/bin
start/stop              ::      /usr/local/apache2/bin/apachectl (start|restart|graceful|graceful-stop|stop|configtest)

===============================================================================

 

#### httpd.conf ####
===============================================================================

Listen 80
# 기본으로 80포트로 들어오는 요청일 읽는다
# 다른 포트를 추가로 지정할 수 있다

ServerRoot "/usr/local/apache"
# 아파치의 홈 디렉토리, 절대경로로 설정한다. 이후에 나오는 대부분의 경로는 ServerRoot의 상대경로로 설정된다.

User apache
Group apache
# 홈페이지 서비스를 직접 담당하는 자식 프로세스들의 실행소유자와 소유 그룹에 대한 계정정보
# 보안을 위해 nobody로 설정하기도 한다.

ServerAdmin root@domain.com
# 웹 문서 로딩 중 에러 발생 시 보여지는 관리자 메일 주소

DocumentRoot "/var/www/html"
# 서버 내의 웹문서가 있는 경로

LoadModule auth_basic_module modules/mod_auth_basic.so
# /usr/local/apache/modules 에 있는 모듈을 동적으로 불러온다

Include conf.d/*.conf
# conf.d 디렉토리 내의 .conf 파일을 불러온다.

ServerName www.example.com
# 클라이언트에서 보여주는 호스트 이름
# 사용중인 도메인이 없다면 IP주소를 입력

Timeout 300
# 클라이언트에서 300초 동안 아무런 요청이 없을 때 연결을 중지

KeepAlive On
# 아파치의 한 프로세스가 특정사용자의 지속적인 요청을 처리

MaxKeepAliveRequests 100
# KeepAlive 가 on일경우에만 유효
# 사용자의 요청을 처리할 때 100이 넘어가면 프로세스를 종료하고 다른 프로세스가 사용자의 요청을 처리
# 하나의 프로세스가 지속적으로 요청을 처리하면 메모리 효율 저하 -> 시스템 성능 저하

KeepAliveTimeout 2
# KeepAlive On인 경우에만 유효
# 2초동안 요청이 없을 경우 timeout

===============================================================================

 


(기타 명령 - 설치)
docker search mysql    // 다운로드 가능한 이미지 출력

===============================================================================

NAME                            DESCRIPTION                                      STARS     OFFICIAL   AUTOMATED
mysql                           MySQL is a widely used, open-source relation…   13869     [OK]
mariadb                         MariaDB Server is a high performing open sou…   5289      [OK]
percona                         Percona Server is a fork of the MySQL relati…   600       [OK]
phpmyadmin                      phpMyAdmin - A web interface for MySQL and M…   747       [OK]
circleci/mysql                  MySQL is a widely used, open-source relation…   29
bitnami/mysql                   Bitnami MySQL Docker Image                       80                   [OK]
bitnami/mysqld-exporter                                                          4
ubuntu/mysql                    MySQL open source fast, stable, multi-thread…   42
cimg/mysql                                                                       0
rapidfort/mysql                 RapidFort optimized, hardened image for MySQL    14
google/mysql                    MySQL server for Google Compute Engine           23                   [OK]
ibmcom/mysql-s390x              Docker image for mysql-s390x                     2
rapidfort/mysql8-ib             RapidFort optimized, hardened image for MySQ…   0
hashicorp/mysql-portworx-demo                                                    0
newrelic/mysql-plugin           New Relic Plugin for monitoring MySQL databa…   1                    [OK]
rapidfort/mysql-official        RapidFort optimized, hardened image for MySQ…   0
databack/mysql-backup           Back up mysql databases to... anywhere!          81
linuxserver/mysql               A Mysql container, brought to you by LinuxSe…   38
mirantis/mysql                                                                   0
docksal/mysql                   MySQL service images for Docksal - https://d…   0
vitess/mysqlctld                vitess/mysqlctld                                 1                    [OK]
linuxserver/mysql-workbench                                                      48
eclipse/mysql                   Mysql 5.7, curl, rsync                           0                    [OK]
drud/mysql                                                                       0
silintl/mysql-backup-restore    Simple docker image to perform mysql backups…   0                    [OK]

===============================================================================

docker pull mysql         // mysql:8.0.31 와 같이 특정 버전을 지정하지 않으면 최신 버전이 설치됩니다.

                                           (mysql 또는 mysql:latest)
                                           아래 URL 에서 제공하는 버전을 확인 할 수 있습니다.
                                           https://hub.docker.com/_/mysql
                                           https://hub.docker.com/_/php
                                           https://hub.docker.com/_/httpd

(기타 명령 - 삭제)
이미지 삭제는 컨테이너 우선 삭제 후 가능합니다.
docker ps                                 // 컨테이너 리스트 출력

===============================================================================

CONTAINER ID   IMAGE               COMMAND                   CREATED          STATUS          PORTS                                                                      NAMES
6cda3429c664   phpmyadmin:latest   "/docker-entrypoint.…"   24 minutes ago   Up 24 minutes   0.0.0.0:8080->80/tcp, :::8080->80/tcp                                      phpmyadmin
da59e94451db   php:8.2.0-fpm       "docker-php-entrypoi…"   36 minutes ago   Up 24 minutes   0.0.0.0:9000->9000/tcp, :::9000->9000/tcp                                  php
e2f8c0642157   mysql:8.0.31        "docker-entrypoint.s…"   12 hours ago     Up 12 hours     0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp                       mysql
a4ac3d6ffd5c   httpd:2.4.54        "httpd-foreground"        33 hours ago     Up 12 hours     0.0.0.0:80->80/tcp, :::80->80/tcp, 0.0.0.0:443->443/tcp, :::443->443/tcp   httpd
===============================================================================

docker rm 6cda3429c664          // 출력된 컨테이너 ID 로 컨테이너 삭제
docker images                            // 이미지 리스트 출력
docker rmi phpmyadmin            // 이미지 삭제

* 참고
이미지 삭제시 아래와 같은 메세지가 출력되는 경우는 REPOSITORY 가 같고 버전의 차이가 없는 경우입니다.
(예 : httpd:2.4.54 와 httpd:latest 가 같은 버전일 경우)
Error response from daemon: conflict: unable to delete 157dcdf23d6c (must be forced) - image is referenced in multiple repositories

아래와 같이 -f 옵션으로 강제 삭제를 하게 되면 두개의 이미지가 동시 삭제 됩니다.

docker rmi -f 157dcdf23d6c


2. 가동

APM 환경 파일을 컨테이너와 연결하여 생성합니다. (root 계정으로 실행)

useradd 93it

passwd 93it
vi /root/docker-compose.yml

===============================================================================

version: '3.9'

services:
    httpd:
        image: httpd:2.4.54
        container_name: httpd
        # 서버 부팅시 컨테이너 가동
        restart: unless-stopped
        ports:
            - "80:80"
        volumes:
              # 웹 소스 파일 경로
            - /home/93it/httpd/html/:/usr/local/apache2/htdocs/

    mysql:
        image: mysql:8.0.31
        container_name: mysql
        restart: unless-stopped
        tty: true
        ports:
            - "3306:3306"
        environment:
            MYSQL_HOST: localhost
            # 초기 mysql root 비밀번호
            MYSQL_ROOT_PASSWORD: qwer
            SERVICE_TAGS: dev
            SERVICE_NAME: mysql
            TZ: Asia/Seoul

    php:
        image: php:8.2.0-fpm
        container_name: php
        restart: unless-stopped
        ports:
            - "9000:9000"
        volumes:
              # php 소스 코드를 사용하기 위해 필수 설정
            - /home/93it/httpd/html/:/var/www/html/
        command:
            - /bin/sh
            - -c
            - |
              # 특정 확장자만 php 소스 코드 사용
              echo "security.limit_extensions = .html .htm .php" >> /usr/local/etc/php-fpm.d/www.conf
              php-fpm

===============================================================================

 

파일 맨 위에 version: '3.9' // compose version 은 docker 버전에 맞추어 사용해야 합니다. 아래 URL 에서 확인이 가능합니다.
https://docs.docker.com/compose/compose-file/compose-versioning/#compatibility-matrix

 

이제 컨테이너를 가동합니다.

docker compose up -d               // 백그라운드로 전체 서비스 (컨테이너) 올리기
* 이 작업이 선행 되어야 컨테이너 별로 제어 (시작/중지) 가 가능함

 

netstat -ntlp

===============================================================================

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      2788/docker-proxy
tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      2834/docker-proxy
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      720/sshd: /usr/sbin
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      2813/docker-proxy
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      625/systemd-resolve
tcp6       0      0 :::3306                 :::*                    LISTEN      2794/docker-proxy
tcp6       0      0 :::9000                 :::*                    LISTEN      2842/docker-proxy
tcp6       0      0 :::22                   :::*                    LISTEN      720/sshd: /usr/sbin
tcp6       0      0 :::80                   :::*                    LISTEN      2819/docker-proxy

===============================================================================


index.html 를 만들고 브라우저로 접속하면 아래 내용 (New index) 이 출력되는것을 확인할 수 있습니다.

echo "New index" > /home/93it/httpd/html/index.html

그리고 변경된 내용이 httpd 컨테이너 내에도 확인됩니다.
( 실 데이터 저장 위치 : /home/93it/httpd/html/ )

docker exec -it httpd /bin/bash  // httpd 컨테이너 으로 접속

아래부터는 httpd 접속
root@771473b9edc0:/usr/local/apache2# cd htdocs
root@771473b9edc0:/usr/local/apache2/htdocs# cat index.html 

===============================================================================

New index

===============================================================================

root@771473b9edc0:exit


현재 컨테이너 구동 상태입니다.
docker compose ps

===============================================================================

NAME                IMAGE               COMMAND                  SERVICE             CREATED             STATUS              PORTS
httpd               httpd:2.4.54        "httpd-foreground"       httpd               33 hours ago        Up 12 hours         0.0.0.0:80->80/tcp, :::80->80/tcp, 0.0.0.0:443->443/tcp, :::443->443/tcp
mysql               mysql:8.0.31        "docker-entrypoint.s…"   mysql               12 hours ago        Up 12 hours         0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp
php                 php:8.2.0-fpm       "docker-php-entrypoi…"   php                 40 minutes ago      Up 28 minutes       0.0.0.0:9000->9000/tcp, :::9000->9000/tcp

===============================================================================

 

docker compose stop php     // 올려진 서비스 (컨테이너) 선택 중지
docker compose start php     // 올려진 서비스 (컨테이너) 선택 시작
docker rm -v php                    // 올려진 서비스 (컨테이너) 삭제
docker compose up -d php    // 하나의 서비스 (컨테이너) 만 구동

 

모든 컨테이너를 더이상 사용하지 않을때 아래와 같이 내립니다.
docker compose down    // 컨테이너 중지 및 삭제

 

docker container 명령어

docker container attach - 컨테이너로 직접 들어간다(it 옵션을 주고 생성된 컨테이너)
docker container exec - 컨테이너로 직접 들어가지 않고 외부에서 컨테이너로 명령을 전달하고 결과값을 밖에서 전달받는다.
docker container run(docker run) - 컨테이너 생성 + 실행
docker run 만 써도 무방하다. container 를 쓰는 이유는 단순 명시하기 위해 쓴다.
docker container start - 중지된 컨테이너를 실행

docker container run 옵션

-it - 대화식 단말 디바이스를 할당하여 Host 가 생성된 컨테이너와 직접 통신이 된다.일반적으로 함께 사용한다.
명령어 마지막에 컨테이너에게 전달할 명령을 써준다. 주로, /bin/bash 또는 /bin/sh를 주로 사용하여 컨테이너 실행시 shell 을 동작시키게 한다
-d - 컨테이너를 백그라운드에서 실행시킨다.
--name - 관리를 위한 목적으로 사용한다. 컨테이너 생성되면 각 컨테이너 별로 id,name이 할당 된다. 하지만 별도로 관리의 편의를 위해 이름을 직접 지정할 수 있다.
다수의 컨테이너를 관리할 때에는 별도의 이름을 입력하는 것이 불필요한 작업이 될 것이다. 이때는 작성하지 않는다
--restart - 처음 생성시, 호스트 재부팅시 컨테이너를 어떻게 실행할 것인가? 웹 서버나 DB와 같이 상시적으로 동작해야하는 컨테이너의 경우에는 초기 생성시 --restart=always로 하여 실행에 문제가 있어도 계속해서 실행을 시도하도록 설정해주는 것이 좋다.
--env(-e) - 시스템 환경 변수를 컨테이너에 작성한다.
-e PYTHON=/usr/lib/python2 -e PY3=/usr/lib/python3.4
-v (--volume) - 볼륨 지정
docker container run -d --name db1 -v testvolume1:/var/lib/mysql mysql:5.7
- testvolume1의 볼륨을 iscsi 로 연결. 컨테이너에서는 이 볼륨을 /dev/sda5 와 같은 자신의 디스크로 인식한다

docker container run -d --name db1 -v /testvolume1:/var/lib/mysql mysql:5.7
- /testvolume1이라는 디렉터리를 nfs 로 연결
-p 호스트의 포트와 매핑하기
보통 동일한 웹 서버 컨테이너 다수를 서비스할 때, 하나의 서버에 다수의 웹 서버 컨테이너를 놓을려면 서버의 각 Port 에 컨테이너 하나씩 지정 해야 하는데,
이는 웹 서비스를 할 때 웹에 접속할 시 Port 를 작성해 접속해야 하므로, 접속에 불편함이있어 이러한 방식은 사용해서는 안된다. 
그렇기 때문에 하나의 서버에 하나의 웹 서버 컨테이너를 놓고 서비스를 해야 하며 Cluster로 관리해야 한다. 이때, 다수의 컨테이너들을 Docker Swarm 과 같은 도구로 관리할 수 있다.
이러한 서버들의 앞에 로드 밸런서를 두고 트래픽을 관리하게 한다.

--link -
rapa@rapa:~$ docker container run -d --name wpdb1 -e MYSQL_ROOT_PASSWORD=test123 -e MYSQL_DATABASE=wordpress -v wpdb1:/var/lib/mysql mysql:5.7
rapa@rapa:~$ docker container run -d --name wp1 -e WORDPRESS_DB_PASSWORD=test123 -e WORDPRESS_DB_USER=root -e WORDPRESS_DB_NAME=wordpress -p 8801:80 --link wpdb1:db1 wordpress
rapa@rapa:~$ docker container exec wp1 cat /etc/hosts
:
:
172.17.0.2 db1 b4ebaf1a6d3a wpdb1 -> link된 컨테이너의 ID,이름,alias명을 IP주소와 함께 등록
172.17.0.3 f9dd0eba6bf7 -> 자신의 ID와 IP주소를 등록

 

 

#https://sysdocu.tistory.com/1742

#https://shanepark.tistory.com/237

#https://velog.io/@yange/%EB%8F%84%EC%BB%A4%EC%97%90-%EB%8C%80%ED%95%98%EC%97%AC-3

 

Ubuntu 20.04 LTS ) Docker 설치하기

Intro Docker는 제가 회사에서 사용하는 노트북의 OS를 Windows 에서 Ubuntu 로 변경하게 된 트리거 였습니다. Docker를 사용하면 정말 편하게 격리된 컨테이너들을 구성해 가상화의 장점을 정말 잘 살릴

shanepark.tistory.com

 

댓글