Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- MongoDB
- Crawling
- docker
- sequelize
- linux
- Network
- OOAD
- Express
- Kotlin
- css
- node.js
- macos
- S3
- mysql
- Util
- OS
- postman
- mongoose
- algorithm
- TypeScript
- AWS
- ubuntu
- DATABASE
- wireshark
- python
- React
- Scheduling
- typeorm
- HTML
- Android
Archives
- Today
- Total
Seongwon Lim
[Python] 파이썬으로 도커 컨테이너(Docker Container) 관리하기 본문
반응형
서론
이번 글에서는 파이썬에서 도커 컨테이너를 관리하는 방법에 대해서 알아본다.
라이브러리 설치
pip3 install docker # pip / pip3 적절히 설치
코드 예제1 - 실행중인 도커 컨테이너 목록 및 상태 출력
import docker
def get_docker_container_status():
try:
# Create Docker clients
client = docker.from_env()
# Import list of running containers
containers = client.containers.list(all=True)
# Return Container List and Status
container_info = {}
for container in containers:
container_info[container.name] = {
'container_id': container.id,
'status': container.status,
}
return container_info
except docker.errors.APIError as e:
return f"Error: {e}"
if __name__ == '__main__':
result = get_docker_container_status()
print(result)
출력 결과는 다음과 같다.
{
'sniffer': {
'container_id': '7c150654117f1624172f010a9cd493beb61f565cff20f0b10e7f792e0afe80fc',
'status': 'exited'
},
'ntp': {
'container_id': 'f44ffc41cde7b0c78eedc309a483cc47e79e5386fa85fd7393ee51611e202481',
'status': 'running'
}
}
코드 예제2 - 컨테이너 이름을 통해 컨테이너 상태 출력
import docker
def get_docker_container_status_using_conName():
try:
# Create Docker clients
client = docker.from_env()
# 컨테이너 이름을 통해 해당 컨테이너의 객체를 리턴으로 받음
container = client.containers.get('ntp')
return {
'container_id': container.id,
'status': container.status,
'container_name': container.name,
'container_ip': container.attrs['NetworkSettings']['Networks']['docker-ntp_default']['IPAddress']
}
except docker.errors.APIError as e:
return f"Error: {e}"
if __name__ == '__main__':
result = get_docker_container_status_using_conName()
print(result)
추가적으로, 컨테이너 IP를 추출할 때 docker-ntp_default가 명시되어 있는 이유는,
docker network ls 명령어를 입력했을 때 나오는 네트워크 이름이다.
출력 결과는 다음과 같다.
{
'container_id': 'f44ffc41cde7b0c78eedc309a483cc47e79e5386fa85fd7393ee51611e202481',
'status': 'running',
'container_name': 'ntp',
'container_ip': '172.21.0.2'
}
코드 예제3 - Exited 상태의 컨테이너 재시작하기
import docker
def restart_stopped_containers(container_name: str):
try:
# Create Docker clients
client = docker.from_env()
# 컨테이너 이름을 통해 해당 컨테이너의 객체를 리턴으로 받음
container = client.containers.get(container_name)
# Restarting a Exited Container
if container.status == 'exited':
container.restart()
return {"status": "Container restarted successfully"}
else:
return {"status": "Container is not in 'exited' state, no restart needed"}
except docker.errors.APIError as e:
return f"Error: {e}"
if __name__ == '__main__':
result = restart_stopped_containers('ntp')
print(result)
result = restart_stopped_containers('sniffer')
print(result)
출력 결과는 다음과 같다.
# container_name : ntp 결과
{'status': "Container is not in 'exited' state, no restart needed"}
# container_name : sniffer 결과
{'status': 'Container restarted successfully'}
재시작 된 컨테이너에 대해서는 docker ps -a 명령어로 확인하면 Up 타임이 최신화 되어 있는 것을 확인할 수 있다.
'Python' 카테고리의 다른 글
[FastAPI] Lifespan을 이용한 생명주기 관리 (Event Handler) (1) | 2024.02.26 |
---|---|
[Python] MacOS pyspark 설치 방법 (0) | 2023.09.19 |
[Python] nohup을 이용한 파이썬 모듈 백그라운드 실행 (0) | 2023.09.06 |
[Python] 문자열 파싱 라이브러리 - Pygrok 설치 및 사용 방법 (0) | 2023.04.14 |
[Python] Scapy 모듈을 이용한 패킷 스니핑 구현하기 (2) | 2023.03.02 |
Comments