programing

도커 엔진과 도커 컨테이너가 작동하는지 확인하는 방법은 무엇입니까?

lovejava 2023. 5. 24. 21:20

도커 엔진과 도커 컨테이너가 작동하는지 확인하는 방법은 무엇입니까?

스크립트에서 다음을 확인해야 합니다.

도커 엔진이 작동합니까?
컨테이너 이름을 고려해 볼 때, 그 도커 컨테이너는 실행되고 있습니까?

[이 질문의 초기 표현은 모호했으며, 일부 사람들은 "체크 도커 엔진"으로 해석하고 다른 사람들은 "체크 도커 컨테이너"로 해석했습니다.]

특정 컨테이너를 찾고 있는 경우 다음을 실행할 수 있습니다.

if [ "$( docker container inspect -f '{{.State.Running}}' $container_name )" == "true" ]; then ...

크래시 루프에 있는 컨테이너가 작동 중임을 표시하지 않고 계속 다시 시작되는 문제를 방지하려면 위의 내용을 확인하여 개선할 수 있습니다.Status필드:

if [ "$( docker container inspect -f '{{.State.Status}}' $container_name )" == "running" ]; then ...

dockerd가 로컬 시스템에서 자체적으로 실행되고 있고 systemd가 설치되어 있는지 확인하려면 다음을 실행할 수 있습니다.

systemctl show --property ActiveState docker

도커에 연결할 수도 있습니다.docker info또는docker version데몬을 사용할 수 없는 경우 오류가 발생합니다.

사용하게 되었습니다.

docker info

도커 엔진이 실행 중인지 bash 스크립트로 확인합니다.

편집: 도커가 실행되지 않을 경우 스크립트를 실패하는 데 사용할 수 있습니다. 다음과 같습니다.

#!/usr/bin/env bash
if ! docker info > /dev/null 2>&1; then
  echo "This script uses docker, and it isn't running - please start docker and try again!"
  exit 1
fi

모든 컨테이너 나열:

docker container ls -a

ls리스트를
-a일체의

열 "상태"를 확인합니다.

다음을 사용하여 도커 상태를 확인할 수 있습니다.systemctl is-active docker

➜  ~  systemctl is-active docker
active

다음과 같이 사용할 수 있습니다.

➜  ~  if [ "$(systemctl is-active docker)" = "active" ]; then echo "is alive :)" ; fi
is alive :)

➜  ~  sudo systemctl stop docker

➜  ~  if [ "$(systemctl is-active docker)" = "active" ]; then echo "is alive :)" ; fi
 * empty response *

OS X 사용자용(Mojave 10.14.3)

다음은 Bash 스크립트에서 Docker가 실행 중인지 테스트하는 데 사용하는 내용입니다.

# Check if docker is running
if ! docker info >/dev/null 2>&1; then
    echo "Docker does not seem to be running, run it first and retry"
    exit 1
fi

모든 도커 명령( 제외)docker -v) , 좋아요docker psDocker가 실행 중이면 유효한 응답이 표시되고, 그렇지 않으면 "Docker 데몬이 실행 중입니까?"라는 메시지가 표시됩니다.

태스크 관리자를 확인할 수도 있습니다.

때때로 전체 컨테이너 이름을 모를 때가 있는데, 이 경우에는 다음과 같이 효과가 있었습니다.

if docker ps | grep -q keyword
then 
    echo "Running!"
else
    echo "Not running!"
    exit 1
fi

실행 중인 모든 컨테이너 프로세스를 나열합니다(docker ps -a또한 실행하지 않는 것을 보여주겠지만, 그것은 제가 필요로 하는 것이 아닙니다), 우리는 특정 단어를 검색합니다.grep키워드가 포함된 실행 중인 컨테이너를 하나 이상 찾지 못한 경우에만 오류가 발생합니다.

컨테이너 상태: true/false

# docker inspect --format '{{json .State.Running}}' container-name
true
#

이 명령을 사용하여 확인할 수 있습니다.systemctl status docker도커의 상태가 표시됩니다.시작하려면 다음을 사용할 수 있습니다.systemctl start docker대신에systemctl당신은 또한 시도할 수 있습니다.service,service docker status그리고.service docker start각각 다음과 같다.

또한 다음 명령을 사용하여 특정 도커 컨테이너가 실행 중인지 여부를 확인할 수 있습니다.

docker inspect postgres | grep "Running"

이 명령은 예를 들어 내 postgres 컨테이너가 실행 중인지 확인하고 출력을 "실행": true로 반환합니다.

이게 도움이 되길 바랍니다.

docker ps -a

모든 도커 컨테이너가 활성 상태인지 비활성 상태인지 확인할 수 있습니다.

첫 번째 질문에 대한 답변은 다음 답변을 참조하십시오. - https://stackoverflow.com/a/65447848/4691279

은 - " 번질는다음같과은명령사수다있니습용할을두문에째"와 같은 할 수 .docker ps --filter "name=<<<YOUR_CONTAINER_NAME>>>"특정 컨테이너가 실행 중인지 여부를 확인합니다.

  • 도커와 컨테이너가 모두 실행 중인 경우 다음과 같은 출력이 표시됩니다.

    $ docker ps --filter "name=nostalgic_stallman"
    
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES       
    9b6247364a03        busybox             "top"               2 minutes ago       Up 2 minutes                            nostalgic_stallman
    
  • 도커가 실행되지 않으면 도커 데몬이 실행되지 않는다는 오류 메시지가 표시됩니다.

  • 도커가 실행되고 있지만 컨테이너가 실행되고 있지 않으면 이 명령어의 출력에 컨테이너 이름이 표시되지 않습니다.

터미널에서 다음 명령을 실행합니다.

docker ps

도커가 실행되고 있지 않으면 다음 메시지가 표시됩니다.

데몬의 오류 응답: dial unix docker.raw.sock: 연결: 연결 거부됨

실행:

docker version

도커가 실행 중이면 다음이 표시됩니다.

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Server: Docker Engine - Community
 Engine:
  Version:          ...
 [omitted]

도커가 실행되고 있지 않으면 다음이 표시됩니다.

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Error response from daemon: Bad response from Docker engine

위의 작업 중 일부를 Gitea 컨테이너의 맥락에서 사용하는 보다 구체적인 예가 있지만, 이름을 기반으로 다른 컨테이너로 쉽게 변환할 수 있습니다.또한, 당신은 아마도 사용할 수 있을 것입니다.docker ps --filter최신 시스템 또는 도커 합성을 사용하지 않는 시스템에서 $GITEA_Container를 설정하는 기능.

# Set to name or ID of the container to be watched.
GITEA_CONTAINER=$(./bin/docker-compose ps |grep git|cut -f1 -d' ')

# Set timeout to the number of seconds you are willing to wait.
timeout=500; counter=0
# This first echo is important for keeping the output clean and not overwriting the previous line of output.
echo "Waiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
#This says that until docker inspect reports the container is in a running state, keep looping.
until [[ $(docker inspect --format '{{json .State.Running}}' $GITEA_CONTAINER) == true ]]; do

  # If we've reached the timeout period, report that and exit to prevent running an infinite loop.
  if [[ $timeout -lt $counter ]]; then
    echo "ERROR: Timed out waiting for $GITEA_CONTAINER to come up."
    exit 1
  fi

  # Every 5 seconds update the status
  if (( $counter % 5 == 0 )); then
    echo -e "\e[1A\e[KWaiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
  fi

  # Wait a second and increment the counter
  sleep 1s
  ((counter++))

done

기본 목표가 "Docker를 시작할 때 컨테이너를 시작하려면 어떻게 해야 합니까?"인 경우

도커의 재시작 정책을 사용할 수 있습니다.

기존 컨테이너에 재시작 정책을 추가하는 방법

도커: 이미 만든 컨테이너에 다시 시작 정책 추가

예:

docker update --restart=always <container>

Mac에서 다음과 같은 이미지를 볼 수 있습니다.

여기에 이미지 설명 입력

도커 아이콘을 마우스 오른쪽 버튼으로 클릭하면 다음이 표시됩니다.

여기에 이미지 설명 입력

또는 다음을 수행합니다.

docker ps

그리고.

docker run hello-world

SSH에서 확인하는 방법.실행:

systemctl

응답인 경우:D-Bus 연결을 가져오지 못했습니다.작업이 허용되지 않습니다.

도커 또는 WSL 컨테이너입니다.

을 확인하는 중.State.Status, State.실행 등을 통해 실행 중인지 알 수 있지만, 컨테이너의 상태를 확인하는 것이 좋습니다.다음은 두 번째 컨테이너에서 명령을 실행하기 전에 두 컨테이너의 상태가 양호한지 확인하기 위해 실행할 수 있는 스크립트입니다.대기 시간/시도 임계값에 도달하면 도커 로그가 출력됩니다.

npm sql-mdb에서 가져온 예입니다.

#!/bin/bash
# Wait for two docker healthchecks to be in a "healthy" state before executing a "docker exec -it $2 bash $3"
##############################################################################################################################
# $1 Docker container name that will wait for a "healthy" healthcheck (required)
# $2 Docker container name that will wait for a "healthy" healthcheck and will be used to run the execution command (required)
# $3 The actual execution command that will be ran (required). When "npm_deploy", all tokens will be included in execution of
#     "npm run jsdoc-deploy" and "npm publish"
attempt=0
health1=checking
health2=checking
while [ $attempt -le 79 ]; do
  attempt=$(( $attempt + 1 ))
  echo "Waiting for docker healthcheck on services $1 ($health1) and $2 ($health2): attempt: $attempt..."
  if [[ health1 != "healthy" ]]; then
    health1=$(docker inspect -f {{.State.Health.Status}} $1)
  fi
  if [[ $health2 != "healthy" ]]; then
    health2=$(docker inspect -f {{.State.Health.Status}} $2)
  fi
  if [[ $health1 == "healthy" && $health2 == "healthy"  ]]; then
    echo "Docker healthcheck on services $1 ($health1) and $2 ($health2) - executing: $3"
    docker exec -it $2 bash -c "$3"
    [[ $? != 0 ]] && { echo "Failed to execute \"$3\" in docker container \"$2\"" >&2; exit 1; }
    break
  fi
  sleep 2
done
if [[ $health1 != "healthy" || $health2 != "healthy"  ]]; then
  echo "Failed to wait for docker healthcheck on services $1 ($health1) and $2 ($health2) after $attempt attempts"
  docker logs --details $1
  docker logs --details $2
  exit 1
fi

X에서 - OS X(M1 칩)로 . - Mac OS X(M1 칩)로 갔습니다.docker version1파운드가 docker info제 경우 아래와 같이 전자를 부르는 것이 약간 더 빠르다는 것이 밝혀졌기 때문입니다.

$ time ( docker info >/dev/null 2>&1 )
( docker info > /dev/null 2>&1; )  0.11s user 0.18s system 39% cpu 0.722 total
$ time ( docker version >/dev/null 2>&1 )
( docker version > /dev/null 2>&1; )  0.05s user 0.05s system 39% cpu 0.238 total

따라서 238ms722ms로 선택하는 속도가 2배 이상 빠릅니다.docker version!

Bash 스크립트에서 Docker 데몬이 실행 중인지 확인하기 위해 다음을 추가했습니다.

# Check if docker is running
if ! docker version >/dev/null 2>&1; then
    echo "Docker does not seem to be running, run it first and retry!"
    exit 1
fi

언급URL : https://stackoverflow.com/questions/43721513/how-to-check-if-the-docker-engine-and-a-docker-container-are-running