What is a Container?
A container is a standard unit of software that packages code and all its dependencies so it runs consistently across computing environments.
-- Docker
Unlike virtual machines, which are slow to boot, containers start in seconds and are much more lightweight.
Virtual Machines vs Containers
Virtual machines (VMs) have been around for a long time. They run a full OS on top of your host machine using a hypervisor. Each VM has its own:
- Full guest operating system
- Allocated CPU, memory, and storage
- Separate system updates and configs
VMs work but are resource-heavy. Containers, on the other hand, share the host OS kernel, keeping apps isolated while being lightweight.
Advantages of Containers:
- Start in seconds vs minutes for VMs
- Lower resource usage — multiple containers on the same host OS
- Same behavior across environments — dev, test, production
Images vs Containers
A container is basically a running instance of an image:
- Image: Read-only blueprint
- Container: Running instance with read-write filesystem
You can launch multiple containers from a single image. Think of it like a class (image) and objects (containers).
Pull Docker Image
Download the "nginx" image:
docker pull library/nginxCheck the images you have:
docker imagesYou can also see the image in Docker Desktop under the "Images" tab.
Run a Container
Start a container from an image:
docker run -d -p hostport:containerport namespace/name:tagMeaning:
- -d: Run detached (in background)
- -p: Forward host port to container port
- hostport: Port on your machine
- containerport: Port inside container
- namespace/name:tag: Image and version
Example:
docker run -d -p 3000:80 library/nginx:latestdocker psVisit http://localhost:3000 to see the running app.
Stop a Container
Two main ways to stop a container:
- docker stop: Sends SIGTERM, graceful shutdown
- docker kill: Sends SIGKILL, forceful stop
Example:
docker psdocker stop CONTAINER_IDRefreshing the webpage now should show the server is down.
Running Multiple Containers
Containers are lightweight. You can run many on the same host.
Example: Start 2 instances of the "nginx" container on different ports:
docker run -d -p 3000:80 library/nginxdocker run -d -p 4000:80 library/nginxOpen each port in the browser to verify:
Use docker ps to see all running containers.
Each container is fully isolated. Even if multiple containers use the same image, changes in one container do not affect others unless you use shared volumes.
Key Takeaways
- Containers package apps and dependencies in isolated, lightweight environments.
- Images define containers; containers are running instances.
- Containers start fast and use fewer resources than virtual machines.
- You can run multiple containers from the same image simultaneously.