Manipulating Docker in Python (Pull Image, Create/Restart/Delete Container, Port Forwarding)

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:

  1. Checks if the Container Exists:
    • Deletes the Container
    • Restarts the Container
  2. 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()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s