Running Your First Docker Container
Now that you have Docker installed on your system, let's explore how to run your first Docker container.
Running a Container
To run a Docker container, you'll need to use the docker run
command. This command will pull the specified image from the Docker registry (if it's not already present on your system) and start a new container based on that image.
Let's start by running a simple "hello world" container:
docker run hello-world
This command will download the hello-world
image from the Docker Hub registry and run a container based on that image. The container will display a "Hello from Docker!" message and then exit.
Interacting with Containers
You can interact with running containers using various Docker commands:
docker ps
: List all running containers
docker stop <container_id>
: Stop a running container
docker start <container_id>
: Start a stopped container
docker exec -it <container_id> /bin/bash
: Open a shell inside a running container
For example, to open a shell inside a running container, you can use the following command:
docker exec -it < container_id > /bin/bash
This will give you a shell prompt inside the container, allowing you to explore and interact with the container's file system and running processes.
Building and Running Custom Images
In addition to running pre-built images, you can also create your own custom Docker images. To do this, you'll need to create a Dockerfile
, which is a text file that contains instructions for building the image.
Here's a simple example of a Dockerfile
:
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
This Dockerfile
will create a new image based on the Ubuntu 22.04 base image, install the Nginx web server, expose port 80, and start the Nginx service when the container is run.
To build the image, you can use the docker build
command:
docker build -t my-nginx-app .
This will create a new image with the tag my-nginx-app
.
To run the container based on this image, you can use the docker run
command:
docker run -d -p 80:80 my-nginx-app
This will start a new container, map port 80 on the host to port 80 in the container, and run the Nginx web server.
Congratulations! You have now learned how to run your first Docker container and interact with it. In the next steps, you can explore more advanced Docker concepts, such as creating your own custom images, managing container networks, and deploying multi-container applications.