Using Docker Images
Pulling Docker images is only the first step. Now, let's learn how to use these images to run containers.
Running a Container from an Image
To create and start a container from an image, use the docker run
command:
docker run ubuntu:22.04 echo "Hello from Ubuntu container"
This command:
- Creates a new container from the
ubuntu:22.04
image
- Runs the
echo "Hello from Ubuntu container"
command inside the container
- Displays the output:
Hello from Ubuntu container
After executing the command, the container stops because it has completed its task.
Running an Interactive Container
To start an interactive shell inside a container, use the -i
(interactive) and -t
(terminal) options:
docker run -it ubuntu:22.04 bash
This gives you a bash shell inside the Ubuntu container where you can run commands:
root@a1b2c3d4e5f6:/## ls
bin dev home lib32 libx32 mnt proc run srv tmp var
boot etc lib lib64 media opt root sbin sys usr
To exit the container, type exit
or press Ctrl+D
:
root@a1b2c3d4e5f6:/## exit
exit
Running a Container in Detached Mode
To run a container in the background (detached mode), use the -d
option:
docker run -d --name nginx-server -p 8080:80 nginx
This command:
- Creates a container named
nginx-server
from the nginx
image
- Runs it in detached mode (
-d
)
- Maps port 8080 on your host to port 80 in the container
- Returns a container ID:
e1d0ac1dcb21a93d9d878dcf40c054eb9f3c2b1bf5ecce7c29b6fa8ce6b219c1
Accessing the Running Container
Now you can access the Nginx web server at http://localhost:8080 in your browser, or use curl
to verify it's working:
curl localhost:8080
This should display the Nginx welcome page HTML:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
...
</html>
Listing Running Containers
To see all running containers, use:
docker ps
This shows information about your running containers:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e1d0ac1dcb21 nginx "/docker-entrypoint.…" 30 seconds ago Up 29 seconds 0.0.0.0:8080->80/tcp nginx-server
Stopping and Removing Containers
To stop a running container:
docker stop nginx-server
To remove a stopped container:
docker rm nginx-server
You've now successfully used Docker images to run containers. This is the fundamental workflow for using Docker in your development and deployment processes.