Docker

A few useful commands when using Docker

1. Pull a Docker image from the Docker Hub repository

docker pull ubuntu:18.04

2. Run a Docker image in interactive mode

docker run -it ubuntu:18.04

3. Stop a running Docker container

docker stop <container-id>

4. Restart a Docker container (assuming it exists) in interactive mode

docker restart <container-id>
docker exec -it <container-id> bash

5. Remove a Docker image

docker rmi ubuntu:18.04

6. Remove a Docker container

docker rm <container-id>

7. Remove all Docker stopped containers

docker container prune

8. List all Docker images

docker images

9. List all Docker containers

docker ps -a

10. How to build a Docker image from a Docker container

Modify a new container docker run –name hw_container ubuntu:latest touch /HelloWorld # Commit the changes you made in that container # to a new image docker commit hw_container hw_image # Remove the changed container docker rm -vf hw_container # Test the new image docker run –rm hw_image # ls -l /HelloWorld # Outputs: # -rw-r–r– 1 root root 0 Apr 15 22:06 # /HelloWorld

11. How to persist data inside a Docker container or share the data with the host?
Basically, there are three ways to do this, i.e., bind mount, volume and tmpfs mount.

Bind mount will mount a directory on the host into the container, such that the data is easily accessible on the host.

Consider a case where you have a directory source and that when you build the source code, the artifacts are saved into another directory, source/target/. You want the artifacts to be available to the container at /app/, and you want the container to get access to a new build each time you build the source on your development host. Use the following command to bind-mount the target/ directory into your container at /app/. Run the command from within the source directory. The $(pwd) sub-command expands to the current working directory on Linux or macOS hosts.

$ docker run -d \
  -it \
  --name devtest \
  -v "$(pwd)"/target:/app \
  nginx:latest

Use docker inspect devtest to verify that the bind mount was created correctly. Look for the Mounts section:

"Mounts": [
    {
        "Type": "bind",
        "Source": "/tmp/source/target",
        "Destination": "/app",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    }
],

This shows that the mount is a bind mount, it shows the correct source and destination, it shows that the mount is read-write, and that the propagation is set to rprivate.

Stop the container:

$ docker container stop devtest

$ docker container rm devtest

Volume is just another way to persist data. It will create a volume managed by Docker inside /var/lib/docker/volumes.