Docker
Docker & Containers
* What Are Containers?
Containers are isolated environments that have their own processes, services, network interfaces, and file mounts. They function like virtual machines but share the same operating system kernel. Containers are not new; technologies like LXC, LXD, and LXCFS have been around for some time. Docker uses LXC internally but offers a simple, user-friendly toolset.
* How Operating Systems Work (Quick Recap)
- An operating system has two main parts: the kernel, which interacts with hardware, and the software layer, which includes the user interface, drivers, and tools. All Linux distributions, such as Ubuntu, CentOS, Fedora, and SUSE, share the same Linux kernel but differ in their software layers.
* How Docker Uses the Kernel
* How Docker Uses the Kernel
- Docker containers share the host operating system kernel. This allows Docker to run any Linux-based distribution on a Linux host. For example, you can run a CentOS container on Ubuntu or a Fedora container on Ubuntu. The container only includes the additional software that distinguishes the operating systems. You cannot run Windows containers on a Linux Docker host because they require a different kernel.
Purpose of Docker
Docker helps you package applications into containers, ship them anywhere, run them anytime, manage multiple instances easily, and scale quickly.
Containers vs Virtual Machines
Purpose of Docker
Docker helps you package applications into containers, ship them anywhere, run them anytime, manage multiple instances easily, and scale quickly.
Containers vs Virtual Machines
| Feature | Containers (Docker) | Virtual Machines |
|---|---|---|
| OS Kernel | Shared | Separate OS per VM |
| Size | Lightweight (MBs) | Heavy (GBs) |
| Boot Time | Few seconds | Few minutes |
| Isolation | Less (shared kernel) | Full isolation |
| Resource Usage | Low | High |
| Cross-OS Support | Linux-on-Linux only | Any OS (Linux, Windows, etc.) |
| Performance | Very fast | Slower |
- Virtual machines need a full operating system inside each machine, making them heavy. Containers reuse the host kernel, which keeps them lightweight.
* Docker Images
- Many ready-made container images are available on Docker Hub. Popular operating systems, applications, and databases include:
- Ubuntu
- MySQL
- Redis
- MongoDB
- Node.js
- Nginx
* Docker Run – The Most Important Command
- To run a container, use the command:
- docker run <image-name>
Examples include:
- docker run nginx
- docker run redis
- docker run ansible
- docker run mongo
- If the image is not present, Docker downloads it from Docker Hub (only the first time). Subsequent runs use the local image. For multiple web servers, start several containers and add a load balancer. If one fails, destroy it and start a new one.
* Summary
- Containers are isolated environments that share the same kernel. Docker simplifies the process of creating and managing containers. Containers are fast, lightweight, and portable, while virtual machines are heavier, fully isolated, and support different operating system kernels. Docker Hub offers thousands of ready-to-run images, and docker run is the key command to start containers.
Lab : Docker Run
* To get the info on Docker CLI, run the command
docker --help. Observe the options listed.- input command : docker --help
- output :
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Common Commands:
run Create and run a new container from an image
exec Execute a command in a running container
ps List containers
build Build an image from a Dockerfile
pull Download an image from a registry
push Upload an image to a registry
images List images
login Log in to a registry
logout Log out from a registry
search Search Docker Hub for images
version Show the Docker version information
info Display system-wide information
Management Commands:
builder Manage builds
buildx* Docker Buildx (Docker Inc., v0.10.4)
compose* Docker Compose (Docker Inc., v2.17.3)
container Manage containers
context Manage contexts
image Manage images
manifest Manage Docker image manifests and manifest lists
network Manage networks
plugin Manage plugins
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes
Swarm Commands:
swarm Manage Swarm
Commands:
attach Attach local standard input, output, and error streams to a running container
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a container's filesystem
events Get real time events from the server
export Export a container's filesystem as a tar archive
history Show the history of an image
import Import the contents from a tarball to create a filesystem image
inspect Return low-level information on Docker objects
kill Kill one or more running containers
load Load an image from a tar archive or STDIN
logs Fetch the logs of a container
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
save Save one or more images to a tar archive (streamed to STDOUT by default)
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
wait Block until one or more containers stop, then print their exit codes
Global Options:
--config string Location of client config files (default "/root/.docker")
-c, --context string Name of the context to use to connect to the daemon
(overrides DOCKER_HOST env var and default context set with
"docker context use")
-D, --debug Enable debug mode
-H, --host list Daemon socket to connect to
-l, --log-level string Set the logging level ("debug", "info", "warn", "error",
"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default
"/root/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/root/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Run 'docker COMMAND --help' for more information on a command.
For more help on how to use Docker, head to https://docs.docker.com/go/guides/
~ ➜
* Spin up a Docker container using the Ubuntu image.
- Note: Use the docker run command for this task.
Input Command : docker run -it ubuntu
- docker run - creates and starts a new container
- -it - runs it interactively (lets you use the terminal inside the container)
- ubuntu - uses the official Ubuntu image (Docker will download it if not already available)
- Once you run the above command, you will be inside Ubuntu shell.
- Verify the status of container
- Input Command : docker ps -a
Docker Container Management Commands
1. docker ps – List Running Containers. This command shows only the containers that are currently running. It displays: - Container ID - Image name - Status - Container name (Docker generates a random name like silly-summit). 2. docker ps -a – List All Containers This command lists all containers, including: - Running - Stopped - Exited - It helps check old containers and their states. 3. Stopping a Container To stop a container, use: - docker stop <container_id_or_name> - You can stop it using either the container ID or the container name. After stopping: - docker ps will show no running containers. - docker ps -a will show the container in an exited state. 4. Notes - Docker automatically gives each container a random name and ID. - If you forget the container name, run docker ps to find it. After stopping, Docker will display the name of the stopped container as confirmation.Lab : Docker, ps, stop
Docker Image & Container Cleanup
* Important Rule:
- You cannot remove an image if any container, whether running or stopped, was created from that image.
- You must first stop all dependent containers, remove them, and then run docker rmi.
* Summary
- docker rm → remove containers
- docker images → view all images
- docker rmi → delete images (only if no container depends on it)
Lab -- docker rm,ri
* Command to see all available images
* Running a container using redis image.
Input Command : docker run --name my-redis -d redis
--name : my-redis (gives container a custom name)
-d : runs in detached mode
redis : official redis image from docker hub
Types of Modes :
| Mode | Flag | Behavior |
|---|---|---|
| Detached | -d |
Runs in background |
| Attached | default | Runs in terminal, shows logs |
| Interactive | -i |
Keeps STDIN open |
| TTY | -t |
Allocates a pseudo-TTY |
| Interactive Shell | -it |
Opens a terminal inside the container |
* Stop the container
* Deleting the Containers
If you want to delete a container, first make sure it is not running.
* Deleting Docker Images.
Docker Images, Containers & Commands
1. Downloading an Image Without Running It - Use docker pull to download an image without starting it: docker pull ubuntu - This command downloads the image and stores it locally. The next docker run command will start right away without needing to download again. 2. Why Ubuntu Container Exits Immediately - When you run: docker run ubuntu - It creates a container, but it exits right away. Why is that? - Containers are designed to run a single process, not a full operating system like a virtual machine. The Ubuntu image does not have a default running process. When there’s no process, the container stops. * Key Rule:- A container only lives as long as the process inside it is alive.
3. Running a Command Inside a Container
- You can assign a task to the container so it remains active for a short time.
- For example:
docker run ubuntu sleep 5
- What happens?
- The container starts and then runs sleep 5. After 5 seconds, the process ends, and the container exits.
4. Long-Running Containers
- If you run:
docker run ubuntu sleep 100
- The container will stay alive for 100 seconds because the sleep process is active during that time. Check the status with:
docker ps
5. Running Commands Inside a Running Container
- Use docker exec to run commands inside an already running container:
docker exec <container_id_or_name> <command>
- For instance:
docker exec mycontainer cat /etc/hosts
- This command prints the /etc/hosts file from that container.
* Summary
- docker pull → downloads image only
- Containers run only as long as the process inside is active
- Ubuntu exits immediately because it has no default process
- docker run ubuntu sleep 5 → runs a temporary process
- docker exec → runs commands inside a running container
Lab : docker pull, exec
* Pull an image
* Run the container in detached mode with previosly created docker image.
Comments
Post a Comment