将docker容器重置/还原为其原始图像的最佳方法

2024-09-30 03:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要能够重新启动/恢复容器到其原始映像状态。简单地做一个docker restart是行不通的(例如,在会话等过程中创建的文件仍然是持久的)。在

目前,我有以下python脚本来完成这项工作:

import subprocess
# Stop and remove a named container if it exists (meaning is running or have exited).
def resetContainer( imageName, containerName ):   
    containerExists=subprocess.check_output(['docker', 'ps','-aqf name=%s' % CONTAINER_NAME])
    if containerExists:
        print('Stop and remove container')
        subprocess.call(['docker', 'stop','%s' % CONTAINER_NAME])
        subprocess.call(['docker', 'rm','%s' % CONTAINER_NAME])
    return;

resetContainer(IMAGE_NAME,CONTAINER_NAME)
# Finally re-create it from image
subprocess.call(['docker', 'run','-d','--name',CONTAINER_NAME,IMAGE_NAME,'tail', '-f','/dev/null'])

但是还有比这更好的方法吗?在

我看过: https://docker-py.readthedocs.io/en/stable/containers.html

但从我所能看到的,我将以同样的行数结束,并在docker“native”命令之上引入一个额外的层的额外“开销”。在


Tags: anddockernameimageifcontaineritcall
2条回答

如果您使用普通docker或docker compose,则需要移除机器上可能存在的容器,并启动新容器以获取新副本。在

# stop a container
docker stop CONTAINER_NAME
# removes the container
docker rm -f  CONTAINER_NAME

如果您的容器使用外部卷(在主机上或其他容器中),您还需要删除它们。如果使用数据库,可能会出现这种情况。在

我在我的机器上使用docker堆栈。这种方法不需要额外的依赖项(与docker compose相反),它为您完成了一个完整的容器重置。在

^{pr2}$

Docker堆栈不清理装载的主机目录。 IMO docker堆栈对容器状态的处理比纯docker运行干净得多。在

@larsks'注释和OkieOth's答案的附加信息:

容器被认为是短暂的,因此您已经在做正确的事情,即:

  1. stopremove旧容器
  2. run一个新的

发件人:Best practices for writing Dockerfiles

General guidelines and recommendations

Containers should be ephemeral

The container produced by the image your Dockerfile defines should be as ephemeral as possible. By “ephemeral,” we mean that it can be stopped and destroyed and a new one built and put in place with an absolute minimum of set-up and configuration.

相关问题 更多 >

    热门问题