우분투에 Docker와 Docker Compose 설치하기

Docker는 애플리케이션을 컨테이너화하여 개발, 배포, 실행을 간소화하는 도구입니다. Docker Compose는 여러 컨테이너를 정의하고 실행하기 위한 도구입니다. 이 글에서는 우분투 시스템에 Docker와 Docker Compose를 설치하는 방법을 안내합니다.

Docker 설치

1. Docker의 공식 GPG 키 추가

우선, Docker의 공식 GPG 키를 시스템에 추가합니다. 이 과정은 Docker 패키지의 무결성을 검증하기 위해 필요합니다.

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

2. Docker 저장소 추가

다음으로, sources.list.d 디렉토리에 Docker 저장소를 추가합니다. 이 저장소는 우분투 패키지 관리자를 통해 Docker를 설치하기 위해 필요합니다.

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

3. Docker 패키지 설치

저장소를 추가한 후, Docker 패키지를 설치할 수 있습니다.

sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io

설치가 완료되면, Docker가 성공적으로 설치되었는지 확인할 수 있습니다.

docker --version

Docker Compose 설치

Docker Compose는 Python으로 작성된 도구이며, Docker 컨테이너 세트의 정의, 실행, 관리를 단순화합니다.

Docker Compose 다운로드 및 설치

최신 버전의 Docker Compose를 다운로드하고 실행 가능한 바이너리 파일로 저장합니다.

sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

다운로드한 파일에 실행 권한을 부여합니다.

sudo chmod +x /usr/local/bin/docker-compose

설치를 확인하기 위해 버전을 체크합니다.

docker-compose --version

이제 우분투 시스템에 Docker와 Docker Compose가 성공적으로 설치되었습니다. 이 도구들을 사용하여 컨테이너화된 애플리케이션의 개발, 배포, 관리를 시작할 수 있습니다.

--

sudo usermod -aG docker $USER

로그아웃 or 재부팅

도커 이미지 관리

Docker에서 사용하지 않는 이미지 삭제하기

Docker 환경에서 저장 공간을 효율적으로 관리하기 위해 사용하지 않는 이미지들을 정리하는 것이 중요합니다. 여기서는 Docker에서 이미지를 삭제하는 몇 가지 방법을 소개합니다.

특정 이미지 삭제

특정 이미지를 삭제하려면 먼저 이미지의 ID나 태그를 알아야 합니다. 이미지 목록을 확인하려면 다음 명령어를 사용합니다:

docker images

이미지 ID나 태그를 사용해 특정 이미지를 삭제할 수 있습니다:

docker rmi [이미지 ID 또는 태그]

예시:

docker rmi abcd1234

이 명령은 이미지 ID가 **abcd1234**인 이미지를 삭제합니다.

사용하지 않는 모든 이미지 삭제

사용되지 않는 모든 이미지를 한 번에 삭제하려면 다음 명령어를 사용합니다:

docker image prune

이 명령은 사용자의 확인을 요구하며, **y**를 입력하면 실행됩니다.

모든 중지된 컨테이너와 사용하지 않는 이미지, 네트워크 삭제

시스템 관련 자원을 종합적으로 정리하고 싶다면 docker system prune 명령을 사용할 수 있습니다:

docker system prune

이 명령은 중지된 모든 컨테이너, 사용하지 않는 이미지와 네트워크를 삭제합니다.

미사용 이미지와 컨테이너, 네트워크, 볼륨 함께 삭제

더욱 광범위한 정리가 필요할 때는 다음과 같은 명령어를 사용합니다:

docker system prune -a --volumes

이 명령은 사용하지 않는 모든 이미지와 컨테이너, 네트워크, 미사용 볼륨까지 삭제하여 Docker 시스템을 철저히 정리합니다. 데이터 손실의 위험이 있으므로 주의해서 사용해야 합니다.


이러한 방법들을 통해 Docker 환경을 깔끔하게 유지하고 필요한 저장 공간을 확보할 수 있습니다. 데이터는 항상 백업 후 작업을 진행하는 것이 안전합니다.

Docker 이미지 관리

Docker 이미지 사용량 확인하기

  1. 이미지 목록과 각 이미지의 크기 보기:
    Docker에서 이미지의 목록과 각 이미지가 차지하는 공간을 보려면 다음 명령어를 사용합니다:

    docker images
    
    

    이 명령은 모든 로컬 이미지를 나열하고, 각 이미지의 리포지토리, 태그, 이미지 ID, 생성된 시간 및 크기를 보여줍니다.

  2. 전체 Docker 시스템의 사용량 보기:
    전체 Docker 시스템(컨테이너, 네트워크, 볼륨 포함)의 사용량을 보려면 다음 명령어를 사용합니다:

    docker system df
    
    

    이 명령어는 이미지, 컨테이너 및 볼륨의 총 사용량, 공유된 공간, 낭비된 공간 등을 보여줍니다.

Docker 이미지 삭제하기

  1. 특정 이미지 삭제하기:
    특정 Docker 이미지를 삭제하려면 다음 명령어를 사용합니다:

    docker rmi [옵션] 이미지이름:태그
    
    

    또는

    docker rmi 이미지ID
    
    

    예를 들어, rabbitmq:management 이미지를 삭제하고 싶다면:

    docker rmi rabbitmq:management
    
    

    이미지를 사용 중인 컨테이너가 있다면 -f 옵션을 추가하여 강제로 삭제할 수 있습니다:

    docker rmi -f 이미지ID
    
    
  2. 사용되지 않는 모든 이미지 삭제하기:
    사용되지 않는 모든 Docker 이미지를 삭제하고 싶을 때는 다음 명령어를 사용합니다:

    docker image prune -a
    
    

    이 명령은 모든 사용하지 않는 이미지를 제거합니다. -a 옵션은 연결되지 않은 모든 이미지를 제거하라는 의미입니다.

이렇게 Docker에서 이미지의 사용량을 확인하고 관리할 수 있으며, 불필요한 이미지를 정리하여 시스템의 공간을 확보할 수 있습니다.

사용하지 않는 컨테이너 일괄 삭제
docker container prune


1. uWSGI 설정 확인

uWSGI 설정 파일 (uwsgi.ini)을 확인하여 die-on-term 옵션이 활성화되어 있는지 확인하세요. 이 설정은 uWSGI가 SIGTERM 신호를 받았을 때 종료되도록 합니다. 이 설정이 활성화되어 있지 않다면 추가해 보세요.

ini코드 복사
[uwsgi]
die-on-term = true

2. uWSGI 프로세스 강제 종료

컨테이너 내부에서 uWSGI 메인 프로세스(PID 1)에게 직접 SIGTERM 또는 SIGKILL 신호를 보내 강제로 종료시켜 보세요.

bash코드 복사
sudo docker exec 82ff3c9f2e83 kill -SIGTERM 1
# 또는
sudo docker exec 82ff3c9f2e83 kill -9 1

3. Docker Compose 조정

docker-compose.yml 파일에서 해당 서비스의 재시작 정책을 조정할 수 있습니다. 재시작 정책을 **no**로 설정하여 컨테이너가 자동으로 재시작하지 않도록 변경할 수 있습니다.

yaml코드 복사
services:
  flask:
    image: image-bati-flask-nginx:latest
    command: "uwsgi uwsgi.ini"
    restart: no  # 자동 재시작하지 않도록 설정

이 설정 후에 docker-compose down 및 **docker-compose up**을 실행하여 환경을 리셋해 보세요.

4. Docker 컨테이너 직접 재시작

모든 설정을 확인한 후, 여전히 문제가 해결되지 않는다면, 컨테이너를 강제로 다시 시작해야 할 수 있습니다.

bash코드 복사
sudo docker restart 82ff3c9f2e83

위 방법들을 시도해 보고 여전히 문제가 해결되지 않는다면, 상세한 설정을 다시 검토하거나 uWSGI 로그를 확인하여 문제의 원인을 좀 더 구체적으로 진단할 필요가 있습니다.


sudo docker exec 82ff3c9f2e83 kill -SIGTERM 1
sudo docker exec 82ff3c9f2e83 kill -9 1
sudo docker exec 82ff3c9f2e83 kill -9 1
sudo docker exec 82ff3c9f2e83 ps aux
docker-compose down
sudo docker kill [컨테이너 ID 또는 이름]
sudo docker-compose stop [서비스 이름]

--

  1. uWSGI PCRE Support:
    • 로그에서 "!!! no internal routing support, rebuild with pcre support !!!" 메시지가 반복해서 나타나고 있습니다. 이는 uWSGI가 Perl 호환 정규 표현식(PCRE) 라이브러리를 포함하여 빌드되지 않았음을 나타냅니다. PCRE 지원은 uWSGI에서 URL 리라이팅이나 내부 라우팅 등 고급 설정을 활용할 때 필요합니다.
    • PCRE 지원이 필요한 경우, uWSGI를 PCRE 라이브러리와 함께 다시 컴파일하거나 설치해야 합니다.

PCRE 지원 추가: Dockerfile에서 uWSGI를 설치할 때 PCRE 라이브러리를 포함하도록 설정합니다. 예를 들어, Dockerfile에 다음과 같은 라인을 추가할 수 있습니다:

Dockerfile코드 복사
RUN apt-get install -y libpcre3 libpcre3-dev && pip install uwsgi

이렇게 하면 PCRE 라이브러리를 설치한 후 uWSGI를 설치합니다.

  1. Root 권한 경고:
    • uWSGI가 root 권한으로 실행되고 있습니다. 이는 보안상 좋지 않습니다. --uid--gid 옵션을 사용하여, non-root 사용자로 uWSGI 프로세스를 실행하는 것이 안전합니다.

If you want to terminate all Docker containers in a more automated way instead of stopping them one by one manually, you can use a script or a single command line to send the SIGTERM signal to the main process (which is usually PID 1) inside each container. Here are a few methods to achieve this:

1. Using a Bash One-Liner

You can use a bash one-liner to iterate over all running containers and send a SIGTERM to the main process inside each container:

bash코드 복사
sudo docker ps -q | xargs -I {} sudo docker exec {} kill -SIGTERM 1

This command does the following:

  • docker ps -q lists the IDs of all running containers.
  • xargs -I {} takes each container ID and replaces {} with that ID in the subsequent command.
  • sudo docker exec {} kill -SIGTERM 1 sends the SIGTERM signal to PID 1 in each container.

2. Script for More Controlled Execution

If you want more control over the process or need to include logging or error handling, you can use a bash script:

bash코드 복사
#!/bin/bash

# Get all running container IDs
containers=$(sudo docker ps -q)

# Loop through all containers and send SIGTERM to PID 1
for container in $containers; do
  echo "Sending SIGTERM to container ID $container"
  sudo docker exec $container kill -SIGTERM 1 || echo "Failed to send SIGTERM to $container"
done

Running the Script

  1. Save the script to a file, for example terminate_containers.sh.
  2. Make it executable with chmod +x terminate_containers.sh.
  3. Run the script: ./terminate_containers.sh.

Note

  • These commands assume you have the necessary permissions to execute sudo docker commands without entering a password. If not, you might need to adjust your sudoers configuration.
  • Using kill -SIGTERM 1 inside containers should be done with understanding that it will terminate the main process, which can result in a graceful shutdown of the container's primary application. Make sure this action is safe for your particular applications.

These methods provide efficient and automated ways to manage container terminations directly from the host system.

Subscribe to Keun's Story newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox. It's free!
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!