Running Containers from Images
Now that you have downloaded some Docker images, let us learn how to create and run containers based on these images.
Running a Basic Container
To run a container from an image, use the docker run
command:
docker run ubuntu echo "Hello from Docker"
This command:
- Creates a new container based on the Ubuntu image
- Runs the command
echo "Hello from Docker"
inside the container
- Exits after the command completes
You should see the output:
Hello from Docker
Running an Interactive Container
To interact with a container, use the -it
flags (interactive terminal):
docker run -it ubuntu bash
This starts a bash shell inside the container. You are now effectively "inside" the container and can run commands.
Try a few commands:
ls
cat /etc/os-release
To exit the container, type:
exit
Listing Running Containers
To see all running containers:
docker ps
Since our containers exited immediately after completion, you might not see any output. To see all containers, including stopped ones:
docker ps -a
This shows all containers, their status, and when they were created/exited.
Container Lifecycle
Containers have a lifecycle:
- Created: Container is created but not started
- Running: Container is currently executing
- Paused: Container execution is paused
- Stopped: Container has exited but still exists
- Removed: Container is deleted
You can remove a stopped container with:
docker rm <container_id>
Replace <container_id>
with the ID shown in the docker ps -a
output.
To automatically remove a container after it exits, use the --rm
flag:
docker run --rm ubuntu echo "This container will be removed after execution"
Running a Web Server Container
Let us try something more practical by running an Nginx web server:
docker pull nginx:alpine
This pulls a lightweight Nginx image based on Alpine Linux.
Now, run a container that maps port 8080 on your host to port 80 in the container:
docker run -d -p 8080:80 --name my-nginx nginx:alpine
This command:
-d
: Runs the container in detached mode (background)
-p 8080:80
: Maps port 8080 on your host to port 80 in the container
--name my-nginx
: Names the container "my-nginx"
Now you can access the Nginx welcome page by navigating to http://localhost:8080
in a web browser, or using curl:
curl http://localhost:8080
You should see the HTML content of the Nginx welcome page.
To stop and remove this container:
docker stop my-nginx
docker rm my-nginx