Run your first container

Start a web server in a container, reach it from your browser, then build and run an image of your own.

· Updated

A container packages an app with everything it needs to run, so it behaves the same on your laptop, a server or a cluster. This guide runs a ready-made web server, then builds an image of your own.

Before you start

  • Docker installed and running. On macOS or Windows, start Docker Desktop first.
  • On a Linux server without Docker, install Docker Engine with Docker's own script:
bash
curl -fsSL https://get.docker.com | sudo sh

Steps

  1. Check Docker can pull and run images:

    bash
    docker run --rm hello-world
  2. Start the nginx web server in the background, sending port 8080 on your computer to port 80 in the container:

    bash
    docker run -d --name web -p 8080:80 nginx:1.27
  3. Open http://localhost:8080 in your browser. You should see Welcome to nginx!

  4. List what's running, and read the container's logs:

    bash
    docker ps
    docker logs web
  5. Stop and remove the container when you're done:

    bash
    docker stop web
    docker rm web

Build your own image

An image is built from a Dockerfile: a list of instructions, each adding a layer. Make a new folder with two files in it.

index.html
<h1>Hello from my first image</h1>
Dockerfile
FROM nginx:1.27
COPY index.html /usr/share/nginx/html/index.html

Then build the image, giving it a name and tag, and run it:

bash
docker build -t my-site:1.0 .
docker run -d --name my-site -p 8080:80 my-site:1.0

Open http://localhost:8080 again and you'll see your own page.

Note

Always pin a version tag such as nginx:1.27 rather than latest, so the image doesn't change under you.

Troubleshooting

Why does it say the port is already allocated?

Something else is using port 8080. Pick another port on your side, for example -p 8081:80, and open that one instead.

Why does it say it cannot connect to the Docker daemon?

Docker isn't running. Start Docker Desktop, or on Linux run sudo systemctl start docker.

Next steps