Running Your Docker Image

In the previous lab, you built a Docker image with a Dockerfile. In this lab, you will now proceed to run that image locally using the Docker engine.

Running a Container #

The Docker run command allows you to execute a command within a container based on the specified container image. If the image is not available locally, the run command can also fetch it from a registry.

To run your container, use the following Docker command. Note that Docker’s publish feature is utilized here to forward the application locally on port 8080, enabling access from Cloud Shell:

docker run --publish 8080:5000 random-facts-app:1.0

Next, open Cloud Shell’s Web Preview and click on “Preview on port 8080”. This action will open a new tab where you will find your application.

Return to the Cloud Shell where you executed the docker command, you will notice that the application is still running. To stop the container, press CTRL + C. Now, let’s instruct Docker to run the container in the background. Re-run the previous command but add the --detach argument as the first parameter to your command. The output will display a container ID, represented by a string of characters and numbers.

Once again, open Cloud Shell’s Web Preview to confirm that your application is visible.

Viewing Running Containers #

The docker ps command is used to display all currently running containers. By using the --all flag, we can also view additional stopped containers. Run the command with and without the flag to observe the difference in output.

You will see an output similar to the following:

CONTAINER ID   IMAGE                  COMMAND                  CREATED         STATUS         PORTS                    NAMES
87590300c30b   random-facts-app:1.0   "flask run --host=0.…"   7 seconds ago   Up 7 seconds   0.0.0.0:8080->5000/tcp   blissful_feynman

Starting and Stopping Containers #

You can start or stop a container using the start and stop commands respectively. To do so, provide the container ID, which can be obtained by listing the running containers with the ps command.

docker stop <containerID>

Once a container is stopped, it is not automatically deleted. To view stopped containers, use the docker ps --all command. Without the --all flag, the stopped container will not be displayed.

If you want to start the container again, you can retrieve the container ID and run the following command:

docker start <containerID>

Pruning Containers #

Earlier, you stopped your container, and as mentioned, it was not deleted. However, Docker provides a way to delete containers through the concept of pruning. To delete the container locally, stop it once again and then execute the following command:

docker container prune

Alternatively, you can use the docker ps command with the --quiet flag to generate a list of container IDs, which can be removed using the docker rm command.