我需要能够重新启动/恢复容器到其原始映像状态。简单地做一个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”命令之上引入一个额外的层的额外“开销”。在
如果您使用普通docker或docker compose,则需要移除机器上可能存在的容器,并启动新容器以获取新副本。在
如果您的容器使用外部卷(在主机上或其他容器中),您还需要删除它们。如果使用数据库,可能会出现这种情况。在
我在我的机器上使用docker堆栈。这种方法不需要额外的依赖项(与docker compose相反),它为您完成了一个完整的容器重置。在
^{pr2}$Docker堆栈不清理装载的主机目录。 IMO docker堆栈对容器状态的处理比纯docker运行干净得多。在
@larsks'注释和OkieOth's答案的附加信息:
容器被认为是短暂的,因此您已经在做正确的事情,即:
stop
和remove
旧容器run
一个新的发件人:Best practices for writing Dockerfiles
相关问题 更多 >
编程相关推荐