Creating volumes
Docker Essentials: Working with Containers
Docker is the most widely used tool for running containers. A container is a lightweight, standalone, and executable software package that includes everything needed to run a piece of software: code, runtime, system tools, system libraries, and settings.
In this article you will learn the basics of working with containers: pulling images, running containers, and managing container lifecycles.
Pulling an image
Before you can run a container, you need an image. An image is a blueprint for a container. You can pull an image from a registry, such as Docker Hub.
docker pull nginx:1.27
This command downloads the nginx image with the tag 1.27. A tag is a label that identifies a specific version or variant of an image.
Running a container
To run a container based on an image, use the docker run command. The following example runs a container from the nginx image, maps port 8080 on your host to port 80 in the container, and runs it in detached mode (-d).
docker run -d -p 8080:80 nginx:1.27
After running this command, you can open http://localhost:8080 in your browser and you will see the default nginx welcome page.
Mounting a volume
Containers are ephemeral: all data written inside a container is lost when the container is removed. To persist data, you can mount a volume from your host into the container. The example below mounts a host directory at /host/pad/naar/data to the container path /data.
docker run -d -v /host/pad/naar/data:/data nginx:1.27
Now any file written to /data inside the container is actually stored on your host in that directory.
Listing and stopping containers
To see all running containers, use docker ps. To stop a container, use docker stop followed by the container ID or name.
docker ps
docker stop <container-id>
Removing containers
Once a container is stopped, you can remove it with docker rm. To also remove the associated volumes, use the -v flag.
docker rm -v <container-id>
Systemd integration
On Linux systems that use systemd, you can manage Docker containers as services. This is useful for automatically starting containers at boot or restarting them after a crash. Create a unit file for your container and enable it with systemctl.
systemctl enable my-container
Next steps
This covered the essentials. Experiment, break things, and read the Docker documentation. Once you are comfortable with the basics, you can explore networking, Docker Compose, and container orchestration.