---
title: "How to Reduce Docker Image Size in Docker Containers"
description: "Is your Docker image size too big and want to make it smaller during builds? Look no futher. Learn how to reduce a Docker image size in this hands-on tutorial."
canonical: "https://adamtheautomator.com/how-to-reduce-docker-image-size-in-docker-containers/"
---

# How to Reduce Docker Image Size in Docker Containers

> Is your Docker image size too big and want to make it smaller during builds? Look no futher. Learn how to reduce a Docker image size in this hands-on tutorial.

Source: https://adamtheautomator.com/how-to-reduce-docker-image-size-in-docker-containers/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How to Reduce Docker Image Size in Docker Containers](https://adamtheautomator.com/wp-content/uploads/2021/11/How-to-Reduce-Docker-Image-Size-in-Docker-Containers.jpg)

# How to Reduce Docker Image Size in Docker Containers

[![](https://secure.gravatar.com/avatar/30af83d8e9a0cf63ad11cbd348c7fdbcb01d92ac46d70d18c96585b7304f3ced?s=192&d=mm&r=g)Amanda Punch](https://adamtheautomator.com/author/amanda-punch/)22 November 20217 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Docker](/tag/docker/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Creating a Docker Image](#creating-a-docker-image)
*   [Reducing a Docker Image Size](#reducing-a-docker-image-size)
*   [Method 1: Applying Multi-Stage Builds](#method-1-applying-multi-stage-builds)
*   [Method 2: Using a Lightweight Parent Image](#method-2-using-a-lightweight-parent-image)
*   [Method 3: Creating a .dockerignore File](#method-3-creating-a-dockerignore-file)
*   [Conclusion](#conclusion)

Is your Docker image taking too long to build and deploy? Is it taking hours to export? Stop wasting time and speed up these processes by developing a smaller image. In this tutorial, you will learn three tricks to reduce your Docker image size.

Let’s get started!

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

*   [Docker Desktop or Engine.](https://docs.docker.com/engine/install/) There are Docker versions available for Linux, Windows, and macOS. This tutorial uses Docker version 20.10.8 build 3967b7d on an Ubuntu 18.04 LTS computer.

Related:[How to Set Up Docker for Mac](https://adamtheautomator.com/docker-for-mac/)

Related:[How to Set Up Docker in WSL \[Step-by-Step\]](https://adamtheautomator.com/how-to-set-up-docker-in-wsl-step-by-step/)

*   [Node.js](https://nodejs.org/en/). This tutorial uses Node.js version 10.10.0 but should work with newer versions, too.
    
*   You’ll need a code editor such as [Visual Studio Code](https://code.visualstudio.com/), [vim, and _nano_](https://adamtheautomator.com/powershell-text-editor/). This tutorial uses _[nano](https://www.nano-editor.org/)._
    

Related:[What You Need to Know about Visual Studio Code](https://adamtheautomator.com/visual-studio-code-tutorial/)

## Creating a Docker Image

You probably already have a Docker image laying around that you want to shrink. Don’t. In this tutorial, you’ll start fresh by creating a Docker image for your testing.

You’ll begin by building a container for a Node.js application The Node.js application you will be using is the [Hello World Express.js](https://expressjs.com/en/starter/hello-world.html) example which displays the text _“Hello World!”_ in your browser.

1\. First, open a terminal session and create a directory where you’ll create your Docker image and associated files. For this example, the working directory will be _~/docker\_demo_.

```bash
# Create the project directory
mdkir ~/docker_demo
# Change the current directory to your working directory
cd ~/docker_demo
```

Next, create three files in your working directory. These files are:

*   index.js – the starting point for your sample application.
*   [_package.json_](https://nodejs.org/en/knowledge/getting-started/npm/what-is-the-file-package-json/) – contains your application’s metadata.
*   _[Dockerfile](https://docs.docker.com/engine/reference/builder/)_ – contains the instructions for building your Docker image.Run the command below in the terminal to create all these files at once.

```bash
touch index.js package.json Dockerfile
```

3\. Open _index.js_ in your code editor, fill it with the code below, and save.

```javascript
const express = require('express')
const app = express()

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => {
  console.log(`Example app listening on port 3000!`)
})
```

4\. Next, open the _package.json_ file for editing, copy and paste the code below, and save.

```json
{
  "name": "hello-world",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "express": "^4.16.2"
  },
  "scripts": {
    "start": "node index.js"
  }
}
```

5\. In the same manner, edit the _Dockerfile_ to populate the code below and save the file.

```docker
# use the Node.js parent image 
FROM node:8 

# set a directory for the app
WORKDIR /app
# copy all the files to the container
COPY . .
# install dependencies
RUN npm install
# define the port number the container should expose
EXPOSE 3000

# run the application
CMD ["npm", "start"]
```

6\. Execute the following [`docker build`](https://docs.docker.com/engine/reference/commandline/build/) command to build your Docker image. The optional `-t` flag tags your image with a name to make it identifiable. This example uses the name _‘my\_app.’_

```docker
docker build -t my_app .
```

7\. When Docker completed building the image, execute the following command to view your image tagged with _‘my\_app.’_

> _The [`grep`](https://man7.org/linux/man-pages/man1/grep.1.html) command is only available on Linux, but to view your image on other operating systems, run the command [`docker images`](https://docs.docker.com/engine/reference/commandline/images/) and look for the image with the tag ‘my\_app.’_

```docker
docker images | grep my_app
```

Related:[How to Use PowerShell’s Grep (Select-String)](https://adamtheautomator.com/powershell-grep/)

As shown in the following image, the Docker image size is 904MB.

![](https://adamtheautomator.com/wp-content/uploads/2021/11/image-294.png)

The Docker image size of _‘my\_app’_

8\. Now verify your image is working correctly. Execute the following [docker run](https://docs.docker.com/engine/reference/run/) command. This command will use your Docker image to create a container where your application will run.

```docker
docker run -p 3000:3000 -ti --rm --init my_app
```

If the application starts correctly, the message _‘Example app listening on port 3000!’_ will be printed in your terminal.

![The output after creating the Docker container](https://adamtheautomator.com/wp-content/uploads/2021/11/image-295.png)

The output after creating the Docker container

9\. To verify your application works, open your browser and navigate to [](http://localhost:3000/)http://localhost:3000/. The text _‘Hello World!’_ should be displayed as shown in the following image.

![The running Node.js application](https://adamtheautomator.com/wp-content/uploads/2021/11/image-296.png)

The running Node.js application

10\. To terminate the application and return to the terminal prompt, press `CTRL+C`.

## Reducing a Docker Image Size

Now that you have a Docker image, it’s time to learn how to reduce your image’s size! The following sections cover three methods to make your Docker image size smaller.

### Method 1: Applying Multi-Stage Builds

Having separate Dockerfile files for development and production was common practice.

The development Dockerfile contained everything necessary to build the application, while the production one included what the application needed to run. This method produces the final production image with the optimum size. But managing two Dockerfiles is unnecessarily complicated.

Since the introduction of [multi-stage builds](https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds) in [version 17.05](https://docs.docker.com/engine/release-notes/17.05/#:~:text=Add%20multi%2Dstage%20build%20support), developers now only need one _Dockerfile_ containing multiple `FROM` instructions to separate the development and production build stages. Thus, selectively copying artifacts from one build stage to another.

Now it’s time to use multi-stage builds in your image!

1\. Open your Dockerfile in the code editor and replace its content with the following code. This new Dockerfile code has two build stages as indicated by the two `FROM` lines.

> _By default, build stages do not have names, and your code can only reference them as the integer in the order they appear (starting at zero) in the Dockerfile. You can append the `as <name>` to the `FROM` line to assign a name to the build stage for better identification_`.`

```docker
# the develop build stage using the node parent image
FROM node:8 as develop

# set a directory for the app
WORKDIR /app
# copy all the files to the container
COPY . .
# install dependencies
RUN npm install

# the production build stage using the node parent image
FROM node:8

# Copy only the build artifact from the first (develop) build stage
# Any intermediate artifacts used to build your application are not included in the final image.
COPY --from=develop /app /

# define the port number the container should expose
EXPOSE 3000

# run the application
CMD ["npm", "start"]
```

2\. Build your new image with the name _my\_app\_multi\_stage\_builds_ by executing the following command.

```docker
docker build -t my_app_multi_stage_builds .
```

3\. After the build, view the updated image size by executing the following command.

```docker
docker images | grep my_app_multi_stage_builds
```

The sample application is small and only has a few intermediate artifacts. But there is still a reduction of 1MB compared to the previous Docker image build.

![The Docker image size after applying multi-stage builds](https://adamtheautomator.com/wp-content/uploads/2021/11/image-297.png)

The Docker image size after applying multi-stage builds

### Method 2: Using a Lightweight Parent Image

Unless you build a Docker image from scratch (using the `FROM scratch` directive), every Docker image has a [parent image](https://docs.docker.com/glossary/#parent-image). The _Dockerfile_ files in the previous sections use `node:8` as the parent image during the build.

If your application does not require a specific operating system version to run, consider swapping your parent image with one more lightweight. If you are using Linux, the most lightweight image in [Docker](https://hub.docker.com/) [](https://hub.docker.com/)[Hub](https://hub.docker.com/) is [Alpine](https://hub.docker.com/_/alpine/?tab=reviews).

Now it’s time to learn how to replace the parent image with Alpine!

1\. Edit your Dockerfile and replace the second `FROM node:8` line with `FROM node:8-alpine`. This new `FROM` instruction, Docker, will be using [node-8-alpine](https://hub.docker.com/layers/mkenney/npm/node-8-alpine/images/sha256-6c28dabc08d4fb4f733e2f79d11f6a7e3dd4b3c0ca5e9eee374d8d5557a1e15b) as the parent image. Now your final image will run on Alpine instead of [Node](https://hub.docker.com/_/node).

```docker
# the first build stage using the node parent image
FROM node:8 as build

# set a directory for the app
WORKDIR /app
# copy all the files to the container
COPY . .
# install dependencies
RUN npm install

# the second build stage using the node-8-alpine parent image
FROM node:8-alpine

# copy the required artifacts to from the first build stage
COPY --from=build /app /
# define the port number the container should expose
EXPOSE 3000

# run the application
CMD ["npm", "start"]
```

2\. Run the command below to build the Docker image with the name _my\_app\_alpine._

```docker
docker build -t my_app_alpine .
```

3\. Finally, view the updated image size by executing the following command.

```docker
docker images | grep my_app_alpine
```

The final Docker image size is now only 75.2MB. A significant reduction of 827.8 MB!

![The Docker image size after using Alpine as a parent image](https://adamtheautomator.com/wp-content/uploads/2021/11/image-298.png)

The Docker image size after using Alpine as a parent image

### Method 3: Creating a .dockerignore File

Docker is a client-server application consisting of the [Docker client](https://docs.docker.com/get-started/overview/#the-docker-client) or CLI and the [Docker daemon](https://docs.docker.com/get-started/overview/#the-docker-daemon), which manages Docker images (and containers, networks, and volumes).

The CLI compiles a _build context_ consisting of the files to include in the image to build. The CLI also searches for a [.dockerignore](https://docs.docker.com/engine/reference/builder/#dockerignore-file) file which lists the files to ignore before sending the build context to the Docker daemon. As a result, copying fewer files reduces the Docker image size.

Now it’s time to apply a .dockerignore file into your build!

1\. First, create a new empty file called _.dockerignore_.

```powershell
touch .dockerignore
```

2\. Next, create a dummy file that you will make Docker ignore during builds. In this example, create a dummy README.md file that is 2MB large.

If on a Linux computer, execute the [fallocate](https://man7.org/linux/man-pages/man1/fallocate.1.html) command below to create the file.

```docker
fallocate -l 2MB README.md
```

If on a Windows computer, run the [fsutil](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil) command instead.

```powershell
fsutil file createnew README.md 2000000
```

3\. Next, build your new Docker image by executing the following command. Since the README.md file is on the same directory, expect this dummy file to be part of the resulting Docker image.

```docker
docker build -t my_app_readme .
```

4\. View the updated image size by executing the following command.

```docker
docker images | grep my_app_readme
```

As expected, with the inclusion of the README.md file, the final Docker image size increased by 2MB.

![The Docker image after adding a 2MB README.md file](https://adamtheautomator.com/wp-content/uploads/2021/11/image-299.png)

The Docker image after adding a 2MB README.md file

5\. Now, exclude all files with the _.md_ extension from the image build. To do so, edit the _.dockerignore_ file and fill it with the following code.

```bash
# ignore markdown files
.md
```

> _Markdown files (.md) typically do not affect an application’s functionality and are generally safe to exclude from builds. Other files you can exclude are build logs, test scripts, your repository’s .git folder, and any files that include sensitive information (such as passwords)._

6\. Now that you’ve updated the ignore file, re-run the Docker image build command as shown below.

```docker
docker build -t my_app_dockerignore .
```

7\. Lastly, run the command below to view the new Docker image size, including the README.md file.

```docker
docker images | grep my_app_dockerignore
```

Now that the README.md file is out of the new build, the Docker image size is down to 75.2MB!

![The Docker image after using a .dockerignore file](https://adamtheautomator.com/wp-content/uploads/2021/11/image-300.png)

The Docker image after using a .dockerignore file

## Conclusion

In this tutorial, you learned the different methods to reduce your Docker image size. You learned how to use multi-stage builds, build from a smaller parent image, and exclude non-essential files.

Next time Docker takes too long to build and deploy, don’t hold back and apply your knowledge to optimize your Docker image size. Which method do you think you will use most?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fhow-to-reduce-docker-image-size-in-docker-containers%2F&text=How%20to%20Reduce%20Docker%20Image%20Size%20in%20Docker%20Containers)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fhow-to-reduce-docker-image-size-in-docker-containers%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fhow-to-reduce-docker-image-size-in-docker-containers%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2023/12/buildah.jpg)

### [Building OCI Images with Buildah](/buildah/)

Master the art of crafting OCI images with buildah for seamless containerization—flexible, efficient, and tailored to your container needs.

![](https://adamtheautomator.com/wp-content/uploads/2023/06/docker-raspberry-pi.jpg)

### [How to Install Docker on Raspberry Pi 4](/docker-on-raspberry-pi/)

Excerpt: Learn how to get started with installing Docker on Raspberry Pi 4 and offload development to a small flexible system.

![](https://adamtheautomator.com/wp-content/uploads/2022/09/Getting-Started-with-Docker-Rancher-Desktop.jpg)

### [Getting Started with Docker Rancher Desktop](/docker-rancher/)

Learn how to get started with the Docker Desktop alternative, Docker Rancher Desktop in this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
