Getting started with docker
Source: Dev.to
What are containers?
Containers are a way of packaging applications together with all required dependencies and configuration, making the application easy to move, share, and deploy.
Before containers, developers working on different operating systems had to manually install all required dependencies to run a project. This setup process could fail or cause inconsistencies between environments.
Example: A React project requires Node.js and project‑specific dependencies. With containers, once the project is packaged, only one tool is required—a container runtime such as Docker—which includes all necessary configurations and dependencies.
- Image – A packaged, read‑only snapshot of an application with its dependencies and configuration.
- Container – The outcome of starting/running an image.
Images and Containers
Docker images are immutable; containers are the running instances of those images.
OS Layers and Virtualization
An operating system consists of the following layers:
- Application layer
- Kernel
- Hardware
Containers virtualize the application layer, resulting in a small bundle size. Services and apps bundled into a Docker container run on top of the application layer and use the kernel of the host machine, as they lack their own kernel.
- Docker containers use the Linux kernel.
- On macOS and Windows, Docker runs inside a lightweight Linux virtual machine.
- Virtual machines can run any operating system regardless of the host OS because they virtualize hardware.
Installation details for each OS can be found on the Docker website.
Installation
After installing Docker, you can avoid using sudo for every Docker command by adding your user to the docker group:
sudo usermod -aG docker ${USER}
Log out and log back in for the change to take effect.
Alternative (non‑persistent) method
Changing the owner of the Docker socket file:
sudo chown $USER /var/run/docker.sock
Note: This approach does not persist across restarts because Docker recreates the socket file on startup.
Managing Docker as a Non‑Root User
Add your user to the Docker group (see above) or use the socket‑ownership method if you need a quick temporary solution.
Common Docker Commands
1. List all images
docker images
2. Run a container from an image
-
Attached mode (Ctrl +C stops the process)
docker run redis:latest -
Detached mode (runs in the background)
docker run -d redis:latest -
With name and port mapping
docker run --name mongodb-4.4 -p 27017:27017 mongo:4.4--nameassigns a name to the container.-p :maps a port from the container to the host.
3. List containers and their metadata
-
Only running containers:
docker ps -
All containers (including stopped ones):
docker ps -a
4. Stop a container
docker stop
5. Start a stopped container
docker start