I wrote this up because I couldn’t find any relatively straight forward answers online that provide an example of consistent usage of Docker in Python.
The code does the following steps:
- Checks if the Container Exists:
- Deletes the Container
- Restarts the Container
- If Container doesn’t exist –
- Pulls the Image down from Docker Central
- Creates the Container with specified Port Mappings and Environment Variables
docker_container_name="test"
docker_image_name="tomcat:latest"
docker_internal_port=1234
docker_external_port=1234
deleteDockerContainerEveryTime = True
restartDockerContainerEveryTime = True
def createDockerContainer():
#create the local instance
import docker
client = docker.from_env()
currentContainers = client.containers.list(all=True)
containerExists = False
for container in currentContainers:
if container.name == docker_container_name:
if deleteDockerContainerEveryTime == True:
container.stop()
container.remove()
break
if restartDockerContainerEveryTime == True and deleteDockerContainerEveryTime == False:
container.restart()
containerExists = True
break
containerExists = True
break
if containerExists == False:
docker_image=docker_image_name
client.images.pull(docker_image)
container = client.api.create_container(
docker_image,
detach=True,
ports=[docker_internal_port, docker_external_port],
host_config=client.api.create_host_config(port_bindings={docker_internal_port: docker_external_port}, publish_all_ports=True),
name=docker_container_name,
environment={
'ENV_VARIABLE_1': 'VALUE1',
'ENV_VARIABLE_2': 'VALUE2',
'ENV_VARIABLE_3': 'VALUE3'
})
currentContainers = client.containers.list(all=True)
for container in currentContainers:
if container.name == docker_container_name:
container.start()
break
createDockerContainer()