Knowledge

Docker: Dockerfiles, building images and registries

Updated 2026-11-08 · Present

Estimated time: 55 minutes.

Quick summary

Step 1 — Check permission to call Docker, then prepare the application and the build context

First confirm that the current user can call the Docker daemon — a user outside the docker group is rejected on the very first command (Docker: post-installation steps). Then create the application directory under $HOME (any user can write there) and put the Dockerfile right at the root of that directory. The build context is the directory passed to the build command — every path in COPY is relative to it (Docker: build context).

When it breaks: A context that is too broad slows the build and carries unrelated files along. Putting the directory under /opt without granting permission means a regular user cannot even create it, and creating it with sudo makes later content edits get rejected.

whoami
id
docker version
mkdir -p ~/inet-web && cd ~/inet-web
echo "<h1>Image duoc tao bang Dockerfile</h1>" > index.html
ls -la
pwd
du -sh .

Observe with:

id to see the groups ; ls -la in the application directory ; du -sh . to estimate the context

Symptoms when it breaks:

How to fix:

  1. Add the user to the docker group and apply it to the current shell right away (or log in again)

    sudo usermod -aG docker "$USER" && newgrp docker && docker version
    
  2. If you want to keep the directory under /opt, give the user ownership before working

    sudo mkdir -p /opt/inet-web && sudo chown "$USER":"$USER" /opt/inet-web && cd /opt/inet-web
    

Note: Pick one way of calling Docker — with sudo or without — and keep it until the end of the lab, because the registry credentials in step 8 are stored separately per user.

Step 2 — Write the Dockerfile

The file name is fixed as Dockerfile. FROM chooses the base; LABEL attaches descriptive metadata; COPY puts content into the image; EXPOSE declares the port the application listens on (Dockerfile reference).

When it breaks: If you use a different file name and forget -f, the build command reports that it cannot find a Dockerfile.

cat > Dockerfile <<'EOF'
FROM nginx:1.27-alpine
LABEL maintainer="hoc-vien"
LABEL description="Trang web tinh dong goi bang Dockerfile"
COPY index.html /usr/share/nginx/html/index.html
EXPOSE 80
EOF
cat Dockerfile

Observe with:

cat Dockerfile

Note: EXPOSE is only a declaration in the metadata; actually publishing the port still needs -p when you run the container.

Step 3 — Write .dockerignore before building

The entire context is sent to the build. .dockerignore keeps junk and sensitive files out of that package — important because images are usually pushed to a registry and may be public (Docker: .dockerignore).

When it breaks: Without .dockerignore, a broad COPY instruction drags .env, private keys and the .git directory into the image.

cat > .dockerignore <<'EOF'
.git
.env
*.key
*.pem
node_modules
dist
EOF
cat .dockerignore

Observe with:

cat .dockerignore ; docker build shows the size of the context it sends

Symptoms when it breaks:

How to fix:

  1. Exclude the sensitive files from the context and rebuild the image

    echo ".env" >> .dockerignore && docker build -t inet-web:v1 .
    
  2. Rotate the secrets that were exposed, do not just remove them from the image

    # revoke and reissue any token/key that was packaged
    

Step 4 — Build the image and read the output step by step

docker build -t name:tag . builds the image instruction by instruction. The output is numbered by the steps that need to be executed (pulling the base, copying content); the rest are steps that write metadata (docker build).

When it breaks: Forgetting the trailing dot means Docker does not know where the build context is and the command fails.

docker image ls | grep inet-web
docker build -t inet-web:v1 .
docker image ls | grep inet-web

Observe with:

docker image ls before and after the build

Symptoms when it breaks:

How to fix:

  1. Run the build from the directory that contains the file to copy

    cd ~/inet-web && docker build -t inet-web:v1 .
    

Step 5 — Verify the image you just created

history lists the layers in order — the upper layers are what was just added, the lower ones are the base image. inspect reads the full metadata, including the LABEL and the declared port (docker image history, docker image).

When it breaks: Without verification you may think you packaged the new version while the build actually reused an old cached layer.

docker image history inet-web:v1
docker image inspect --format "{{.Config.Labels}}" inet-web:v1
docker image inspect --format "{{.Config.ExposedPorts}}" inet-web:v1
docker image inspect --format "{{.Os}} {{.Architecture}} {{.Size}}" inet-web:v1

Observe with:

docker image history inet-web:v1 ; docker image inspect --format ... inet-web:v1

Step 6 — Run the image you built and tell the two kinds of log apart

Run the image you just created like any other image. The log of the build process is in the output of the build command; docker logs only shows the log while the container is running — two different sources that do not replace each other.

When it breaks: Looking for the cause of a failed build in docker logs will never find it, because build errors are not there.

docker run -d --name inet-web -p 8080:80 inet-web:v1
docker ps
curl -s http://localhost:8080
docker logs inet-web

Observe with:

curl http://localhost:8080 ; docker logs inet-web

Note: The page content is the index.html file that was baked into the image — running this image on any machine produces exactly that content.

Step 7 — Edit the content and build a new version

Following on from the immutability lesson in Part 1: the right way to change content permanently is to edit the source and build a new image with a new tag, instead of hot-editing inside a running container (Docker: build cache).

When it breaks: Reusing the same tag for two different contents makes it impossible to trace which version is running in the real environment.

echo "<h1>Phien ban 2 — do hoc vien tu build</h1>" > index.html
docker build -t inet-web:v2 .
docker image ls | grep inet-web
docker run -d --name inet-web-v2 -p 8081:80 inet-web:v2
curl -s http://localhost:8081

Observe with:

docker image ls (you see two tags) ; curl to compare the content of the two containers

Step 8 — Tag and push to a registry

An image stays on the build machine until it is pushed. Tag it in the form <registry>/<tai-khoan>/<kho>:<tag>, log in, then push; once it is pulled elsewhere, it can run there (docker push, docker login). The <tai-khoan> part is the account name on the registry, not the Linux username logged in on the machine.

When it breaks: A tag with the wrong account/repository name gets the push rejected for permissions; pulling anonymously beyond the limit breaks the pipeline. Logging in with sudo and then pushing as a regular user is also rejected, because the two commands read two different credential files.

docker login
docker tag inet-web:v2 docker.io/<tai-khoan>/inet-web:v2
docker push docker.io/<tai-khoan>/inet-web:v2
docker rmi docker.io/<tai-khoan>/inet-web:v2
docker pull docker.io/<tai-khoan>/inet-web:v2

Observe with:

docker push prints per-layer progress ; docker info | grep -i username to see which account you are logged in with ; try docker pull from another machine

Symptoms when it breaks:

How to fix:

  1. Re-tag with the correct account and target repository name, then push again

    docker tag inet-web:v2 docker.io/<tai-khoan>/inet-web:v2
    
  2. Log in again as the very user who will run the push, then cross-check the account

    docker login
    docker info | grep -i username
    
  3. Log in with an access token instead of pulling anonymously

    docker login -u <tai-khoan>
    

Note: Use an access token for docker login, not the account password; never commit the token to source code. Login and push must be done by the same user (both with sudo or both without).

Common misconceptions

The Docker daemon listens on the socket /var/run/docker.sock, owned by root:docker, which only the owner and members of the group can read/write; a user outside the group gets permission denied on the very first command (Docker: post-installation steps for Linux). Adding a user to the docker group opens up that access, but it also means that user can run a container that mounts the host's entire filesystem with root privileges — the Docker documentation states plainly that this is root-equivalent access, not a lower level of privilege. Alongside this is a detail that is easy to trip over: docker login writes credentials to the $HOME/.docker/config.json of the user who runs the command, so sudo docker login stores them in /root/.docker/config.json (docker login). Consequence: logging in with sudo and then pushing without sudo (or the other way round) reports a permission denial even though the registry account is perfectly valid — choose one way of calling Docker for both login and push.

EXPOSE records in the image metadata "which port the application inside listens on", for readers and some automation tools (Dockerfile reference). It does not create any forwarding rule on the host. Opening the path from a host port to a container port is decided by -p (publish) at docker run time; without -p, the service exists only on Docker's internal network. Consequence: when an application "runs but cannot be reached", check the PORTS column of docker ps first, rather than editing EXPOSE in the Dockerfile and rebuilding.

Docker builds an image instruction by instruction and reuses old layers when the inputs of that layer have not changed; once a layer is invalidated, every layer after it is invalidated too (Docker: build cache). Because source code changes more often than the dependency list, putting the COPY of the source after the dependency install step preserves the cache of the install step — the most time-consuming one. Doing it the other way round means every one-line code edit reinstalls all dependencies. Consequence: instruction order is a decision about the speed of the development loop and the duration of the CI pipeline, not a matter of aesthetics.

The build command packages the context directory (the dot in docker build -t name .) and sends it; .dockerignore decides which parts are excluded from that package (Docker: .dockerignore). A COPY . . instruction brings everything left in the context — including .env, private keys, and the .git directory with its history. The image is then usually pushed to a registry and may be public, which means anyone who pulls it can unpack these files. Consequence: write .dockerignore as soon as you create the Dockerfile, and for secrets needed at build time, use the build secret mechanism instead of copying them into the image (Docker: build secrets).

Minimal images (slim/alpine) and distroless keep only the runtime parts the application needs, dropping the shell and the package manager (GoogleContainerTools/distroless). Fewer packages mean fewer vulnerabilities to track and patch. In exchange, with no shell you cannot docker exec in to run diagnostic commands — you must diagnose through logs, a helper container or a separate debug image. This follows the same philosophy as immutable operating systems used for container infrastructure: once installed, nothing is modified at the system level. Consequence: choosing a base image is a conscious trade-off between ease of diagnosis and attack surface, so decide it by environment (development or production) rather than by habit.

docker build stores the image in that machine's local store; distributing it elsewhere requires tagging it in the form <registry>/<tai-khoan>/<kho>:<tag> and then docker login and docker push (docker push, docker login). This is exactly a link in the CI/CD flow: the source code is tested, built into an image, versioned, pushed to a registry, and then the target environment pulls exactly that version. A registry can be a public service or self-hosted when you need privacy. Consequence: naming and versioning conventions for images need to be agreed from the start, because they are what real environments rely on to pull exactly the version that should run.

Hands-on 1 — Your first Dockerfile and building your own image

20 minutes

Package a static page into your own image — the step from "using other people's images" to "creating your own" (Dockerfile reference).

docker build -t inet-web:v1 .

Observation: docker image ls | grep inet-web ; docker image history inet-web:v1

1. Check the user and the permission to call Docker: whoami, id, docker version. If it reports permission denied, run sudo usermod -aG docker "$USER" then newgrp docker — or use sudo for every docker command and keep it that way.

docker version prints both the Client and the Server sections.

2. Create the application directory under $HOME (for example ~/inet-web) and an index.html file with a line of your own content.

The directory contains exactly one content file, created without needing sudo.

3. Write the Dockerfile: FROM an nginx base image, a descriptive LABEL, COPY index.html into the web root, EXPOSE 80.

The Dockerfile exists, and reading it back shows all 4 instructions.

4. Write a .dockerignore that excludes .git, .env, *.key, *.pem.

The .dockerignore file exists before the build.

5. Build: docker build -t inet-web:v1 . then docker image ls | grep inet-web.

The build runs through its steps and the image inet-web:v1 appears in the list.

Analysis

Observation: The build output is numbered by the instructions that need to run; the new image sits in the local store.

Mechanism: Each instruction builds a layer on top of the base image; the context is the directory passed at the end of the command.

Lesson: Building your own image is the right way to change content permanently, instead of hot-editing inside a container.

Troubleshooting:

Hands-on 2 — Verify and run the image you just built

15 minutes

Confirm that the image really contains the packaged content, and tell the build log apart from the container log (docker image history).

docker run -d --name inet-web -p 8080:80 inet-web:v1

Observation: curl http://localhost:8080 ; docker logs inet-web

1. Look at the layers: docker image history inet-web:v1.

The top layer is what was just added; below it are the layers of the base image.

2. Read the metadata: docker image inspect --format "{{.Config.Labels}}" inet-web:v1 and {{.Config.ExposedPorts}}.

You see the correct LABEL and the port declared with EXPOSE.

3. Run a container on port 8080 and then curl -s http://localhost:8080.

The page returns the packaged content, not the default page of the base image.

4. Edit index.html, build inet-web:v2, run it on port 8081 and compare the content of the two ports.

The two ports return two different contents — each tag is an independent version.

Analysis

Observation: The content travels with the image, not with the container; two tags with different content coexist.

Mechanism: COPY bakes the file into an image layer, so every container created from that image has exactly that content.

Lesson: Versioning images is how you can trace which version the real environment is running.

Troubleshooting:

Hands-on 3 — Pushing the image to a registry

20 minutes

An image can only be used on another machine after it is pushed to a registry — the last link in the build and distribution flow (docker push).

docker push docker.io/<tai-khoan>/inet-web:v2

Observation: The per-layer push progress ; try deleting the local image and pulling it again

1. Register an account on a registry (Docker Hub or Quay), create an access token and run docker login — as the very user who will do the push. Cross-check with docker info | grep -i username.

The login succeeds and the cross-check command shows the right account; use the token, not the account password.

2. Tag the image for the destination: docker tag inet-web:v2 docker.io/<tai-khoan>/inet-web:v2.

docker image ls shows an additional full name pointing to the same image ID.

3. Push it: docker push docker.io/<tai-khoan>/inet-web:v2.

Each layer is pushed; the repository shows the image on the registry's web UI.

4. Delete the local copy and pull it again: docker rmi ... and docker pull ....

The pull succeeds and running it again gives the right content — the image now lives independently of the build machine.

Analysis

Observation: After the push, the image exists elsewhere and can be pulled from any machine.

Mechanism: The registry stores the layers by digest; a tag is a label pointing to a specific version.

Lesson: Naming and versioning conventions are what real environments rely on to pull exactly the version that should run.

Troubleshooting:

Review questions

Question 1. What does EXPOSE 80 in a Dockerfile do when the container runs?

  1. Automatically opens port 80 on the host
  2. It only records a declaration in the image metadata; to reach it from outside you still need -p at run time
  3. Blocks all other ports of the container
  4. Forces the application inside to listen on port 80

Answer: It only records a declaration in the image metadata; to reach it from outside you still need -p at run time. EXPOSE is a documentation-style declaration in the metadata and creates no port forwarding on the host; actual publishing is decided by -p at docker run time (Dockerfile reference).

Question 2. What does the trailing dot in docker build -t inet-web:v1 . mean?

  1. Clears the build cache
  2. The build context is the current directory — what gets packaged and sent, and where the Dockerfile is looked up
  3. Builds in silent mode
  4. Marks the image as the production version

Answer: The build context is the current directory — what gets packaged and sent, and where the Dockerfile is looked up. The last argument of the command is the build context: the directory packaged and sent to the build, which is also where the Dockerfile is looked up and the root for resolving COPY paths (Docker: build context).

Question 3. Why should the dependency install step come BEFORE the source copy step in a Dockerfile?

  1. Because Docker requires that order
  2. Because source code changes more often; placed afterwards, the dependency install step can still reuse its cache
  3. Because the image will be smaller
  4. Because it is more secure

Answer: Because source code changes more often; placed afterwards, the dependency install step can still reuse its cache. A changed layer forces every layer after it to be rebuilt; putting the rarely changing part first preserves the cache for the dependency install step, which takes the most time (Docker: build cache).

Question 4. What problem does .dockerignore solve?

  1. Hides containers from docker ps
  2. Excludes junk and sensitive files from the build context so they do not slip into an image that will be released
  3. Ignores errors during the build
  4. Limits the image size

Answer: Excludes junk and sensitive files from the build context so they do not slip into an image that will be released. The entire context is sent to the build and may be copied into the image; .dockerignore decides which parts are excluded — important because images are usually pushed to a registry (Docker: .dockerignore).

Question 5. What does a distroless image trade off?

  1. It runs slower
  2. A smaller attack surface, but with no shell you cannot exec in to diagnose
  3. It cannot run on Linux
  4. It cannot be pushed to a registry

Answer: A smaller attack surface, but with no shell you cannot exec in to diagnose. Distroless keeps only the runtime, dropping the shell and the package manager — fewer vulnerabilities to patch, in exchange for diagnosing through logs or a separate debug image (GoogleContainerTools/distroless).

Question 6. After a build finishes, how do you make the image usable on another machine?

  1. The other machine automatically sees the image over the internal network
  2. Tag it as <registry>/<user>/<repo>:<tag>, docker login and then docker push; the other machine pulls it
  3. Copy the /var/lib/docker directory to the other machine
  4. Nothing needs to be done if the Docker versions are the same

Answer: Tag it as <registry>/<user>/<repo>:<tag>, docker login and then docker push; the other machine pulls it. docker build only stores the image in that machine's local store; distribution requires tagging it for the right destination, logging in and pushing to a registry (docker push).

Question 7. Which command shows the base image and the layers added during the build?

  1. docker logs
  2. docker image history
  3. docker stats
  4. docker system df

Answer: docker image history. docker image history lists the layers in order along with when and by which command they were created — the top layer is what was just added (docker image history).

Question 8. "sudo docker login" succeeds, but "docker push" (without sudo) reports denied even though the tag has the right account. What is the cause?

  1. The registry has not updated yet; wait a few minutes
  2. Credentials are stored per user: sudo writes to /root/.docker/config.json, while the push command reads the regular user's $HOME/.docker/config.json
  3. The image is too large so it is rejected
  4. You have to rebuild the image with sudo

Answer: Credentials are stored per user: sudo writes to /root/.docker/config.json, while the push command reads the regular user's $HOME/.docker/config.json. docker login writes credentials to the $HOME/.docker/config.json of the user who runs the command, so logging in with sudo and pushing as a regular user are two different sessions — log in again as the very user who will push, or use sudo for both commands (docker login).

Question 9. What does adding a user to the docker group mean in terms of privileges?

  1. It grants limited permissions, much safer than root
  2. It allows calling the Docker daemon through the socket, but that access is equivalent to root on the host because a container can mount the entire filesystem
  3. It only allows running containers, not building images
  4. It has no effect, it is just for typing commands more conveniently

Answer: It allows calling the Docker daemon through the socket, but that access is equivalent to root on the host because a container can mount the entire filesystem. The socket /var/run/docker.sock belongs to root:docker; joining the group lets you call the daemon, and since the daemon runs as root, that user can create a container that mounts the host filesystem with root privileges (Docker: post-installation steps).

Question 10. A CI pipeline fails with "toomanyrequests: You have reached your pull rate limit". What is the most sensible fix?

  1. Rebuild repeatedly until it passes
  2. Log in with an account that has its own limit, or use an internal registry as an intermediate mirror
  3. Switch to a larger image
  4. Delete the build cache

Answer: Log in with an account that has its own limit, or use an internal registry as an intermediate mirror. The limit is counted per account pulling images; logging in with your own account or putting an internal registry in front as an intermediate mirror for heavily used images cuts the dependency on the public limit (Docker Hub: usage limits).

Flashcards