Sign In
Sign In

How to Create and Optimize Docker Images

How to Create and Optimize Docker Images
Hostman Team
Technical writer
Docker
22.01.2025
Reading time: 12 min

In today's environment, most companies actively use the Docker containerization system in their projects, especially when working with microservice applications. Docker allows you to quickly deploy any applications, whether monolithic or cloud-native. Despite the simplicity of working with Docker, it's important to understand some nuances of creating your own images. In this article, we will explore how to work with Docker images and optimize them using two different applications as examples.

Prerequisites

To work with the Docker containerization system, we will need:

  • A cloud server or a virtual machine with any pre-installed Linux distribution. We will be using Ubuntu 22.04.

  • Docker installed. See our installation guide

You can also use a pre-configured image with Docker. To do this, go to the Cloud servers section in your Hostman control panel, click Create server, and select Docker in the Marketplace tab.

Working with Docker Images

Docker images are created by other users and stored in registries—special repositories for images. Registries can be public or private. Public repositories are available to all users without requiring authentication. Private registries, however, can only be accessed by users with appropriate login credentials. Companies widely use private repositories to store their own images during software development.

By default, Docker uses the public registry Docker Hub, which any user can use to publish their own images or download images created by others. When a user runs a command such as docker run, the Docker daemon will, by default, contact its standard registry. If necessary, you can change the registry to another one.

To create custom Docker images, a Dockerfile is used—a text file containing instructions for building an image. These instructions use 18 specially reserved keywords. The most common types of instructions include the following:

  • FROM specifies the base image. Every image starts with a base image. A base image refers to a Linux distribution, such as Ubuntu, Debian, Oracle Linux, Alpine, etc. There are also many images with various pre-installed software, such as Nginx, Grafana, Prometheus, MySQL, and others. However, even when using an image with pre-installed software, some Linux OS distribution will always be specified inside.

  • WORKDIR creates a directory inside the image. Its functionality is similar to the mkdir utility used to create directories in Linux distributions. It can be used multiple times in one image.

  • COPY copies files and directories from the host system into the image. It is used to copy configuration files and application source code files.

  • ADD is similar to the COPY instruction, but in addition to copying files, ADD allows downloading files from remote sources and extracting .tar archives.

  • RUN executes commands inside the image. With RUN, you can perform any actions that a user can perform in a Bash shell, including creating files, installing packages, starting services, etc.

  • CMD specifies the command that will be executed when the container is started.

Example: Creating an Image

As an example, we will create an image with a simple Python program.

  1. Create a project directory and move into it:

mkdir python-calculator && cd python-calculator
  1. Create a file console_calculator.py with the following content:

print("*" * 10, "Calculator", "*" * 10)
print("To exit from program type q")

try:
 while True:
    arithmetic_operators = input("Choose arithmetic operation (+ - * /):\n")
    if arithmetic_operators == "q":
        break
    if arithmetic_operators in ("+", "-", "*", "/"):
        first_number = float(input("First number is:\n"))
        second_number = float(input("Second number is:\n"))
        print("The result is:")
        if arithmetic_operators == "+":
            print("%.2f" % (first_number + second_number))
        elif arithmetic_operators == "-":
            print("%.2f" % (first_number - second_number))
        elif arithmetic_operators == "*":
            print("%.2f" % (first_number * second_number))
        elif arithmetic_operators == "/":
            if second_number != 0:
                print("%.2f" % (first_number / second_number))
            else:
                print("You can't divide by zero!")      
    else:
        print("Invalid symbol!")

except (KeyboardInterrupt, EOFError) as e:
    print(e)
  1. Create a new Dockerfile with the following content:
FROM python:3.10-alpine

WORKDIR /app

COPY console_calculator.py .

CMD ["python3","console_calculator.py"]

For the base image, we will use python:3.10, which is based on a lightweight Linux distribution called Alpine. We will discuss the use of Alpine in more detail in the next chapter.

Inside the image, we will create a directory app, where the project file will be located.

The container will be launched using the command "python3", "console_calculator.py".

  1. To build the image, the docker build command is used. Each image must also be assigned a tag. A tag is a unique identifier that can be assigned to an image. The tag is specified using the -t flag:

docker build -t python-console-calculator:01 .

The period at the end of the command indicates that the Dockerfile is located in the current directory.

You can display the list of created images using:

docker images

Image24

To launch the container, use: 

docker run --rm -it python-console-calculator:01

Image1

Let's test the functionality of the program by performing a few simple arithmetic operations:

Image3

To exit the program, you need to press the q key.

Since we specified the --rm flag when starting the container, the container will be automatically removed.

You can also run the container in daemon mode, i.e., in the background. To do this, include the -d flag when starting the container:

docker run -dit python-console-calculator:01

After that, the container will appear in the list of running containers:

Image10

When starting the container in the background to access our script, you need to use docker exec, which executes a command inside the container. First, you need to start a shell (bash or sh), then manually run the script inside the container.

To do this, use the docker exec command, passing the sh command as an argument to open the shell inside the container (where 4f1b8b26c607 is the unique container ID displayed in the CONTAINER ID column of the docker ps output):

docker exec -it 4f1b8b26c607 sh

Then, run the script manually:

python console_calculator.py

Image16

To remove a running container, you need to use the docker rm command and pass the container's ID or name. You also need to use the -f flag, which will force the removal of a running container:

docker rm -f 186e8f43ca60

Optimizing Docker Images

When creating Docker images, there is one main rule: finished images should be compact and occupy as little space as possible. Additionally, the smaller the image, the faster it is built. This can play a key role when using CI/CD methods or when releasing software in the Time to Market model.

Proper Selection of the Base Image

As the first recommendation, it's important to choose the base image wisely. For example, instead of using various Linux distribution images like Ubuntu, Oracle Linux, Rocky Linux, and many others, you can directly choose an image that already comes with the required programming language, framework, or other necessary technology. Examples of such images include:

  • node for working with the Node.js platform
  • A pre-built image with Nginx
  • ibmjava for working with the Java programming language
  • postgres for working with the PostgreSQL databases
  • redis for working with the NoSQL Redis

Using a specific image instead of an operating system image has the following advantages:

  • There is no need to install the main tool (programming language, framework, etc.), so the image won't be "cluttered" with unnecessary packages, preventing an increase in size.

  • Images that come with pre-installed software (like Nginx, Redis, PostgreSQL, Grafana, etc.) are always created by the developers of the software themselves. This means that users do not need to configure the program to run it (except in cases where it needs to be integrated with their service).

Let's consider this recommendation with a practical example. We will use a simple Python program that prints "Hello from Python!".  First, we will build an image using debian as the base image.

  1. Create and navigate to the directory where the project files will be stored:

mkdir dockerfile-python && cd dockerfile-python
  1. Create the test.py file with the following content:

print("Hello from Python!")
  1. Next, create a Dockerfile with the following content:

FROM debian:latest

COPY test.py .

RUN apt update 
RUN apt -y install python3

CMD ["python3", "test.py"]

To run Python programs, you also need to install the Python interpreter.

  1. Then, build the image:

docker build -t python-debian:01 .

Image20

Let’s check the Docker image size: 

docker images

Image8

The image takes up 185MB, which is quite a lot for an application that just prints a single line to the terminal.

Now, let's choose the correct base image, which is based on the Alpine distribution.

Another feature of base images is that for many images, there are special versions in the form of slim and alpine images, which are even smaller. Let's look at the example of the official Python 3.10 image. The python:3.10 image takes up a whole 1 GB, whereas the slim version is much smaller—127 MB. And the alpine image is only 50 MB.

Image17

Slim images are images that contain the minimum set of packages necessary to run a finished application. These images lack most packages and libraries. Slim images are created from both regular Linux distributions (such as Ubuntu or Debian) and Alpine-based distributions.

Alpine images are images that use the Alpine distribution as the operating system— a lightweight Linux distribution that takes up about 5 MB of disk space (without the kernel). It differs from other Linux distributions in that it uses a package manager called apk, lacks the system initialization system, and has fewer pre-installed programs.

When using both slim and Alpine images, it is essential to thoroughly test your application, as the required packages or libraries might be missing in such distributions.

Now, let's test our application using the Python image with Alpine.

  1. Return to the previously used Dockerfile and replace the base image from debian to the python:alpine3.19 image. You should also remove the two RUN instructions, as there will be no need to install the Python interpreter:

FROM python:alpine3.19

COPY test.py .

CMD ["python3", "test.py"]
  1. Use a new tag to build the image:

Image21

  1. List all the Docker images. Check the image size and compare with the previous one: 

Image11

Since we chose the correct base image with Python already preinstalled, the image size was reduced from 185 MB to 43.8 MB.

Reducing the Number of Layers

Docker images are based on the concept of layers. A layer represents a change made to the image's file system. These changes include copying/creating directories and files or installing packages. It is recommended to use as few layers as possible in the image. Among all Dockerfile instructions, only the FROM, COPY, ADD, and RUN instructions create layers that increase the final image size. All other instructions create temporary intermediate images and do not directly increase the image size.

Let's take the previously used Dockerfile and modify it according to new requirements. Suppose we need to install additional packages using the apt package manager:

FROM debian:latest

COPY test.py .

RUN apt update 
RUN apt -y install python3 htop net-tools mc gcc

CMD ["python3", "test.py"]

Build the image:

docker build -t python-non-optimize:01 .

Check the size of the created Docker image:

docker images

Image14

The image size was 570 MB. However, we can reduce the size by using fewer layers. Previously, our Dockerfile contained two RUN instructions, which created two layers. We can reduce the image size by combining the apt update and apt install commands using the && symbol, which in Bash means that the next command will only run if the first one completes successfully.

Another important point is to remove cache files left in the image after package installation using the apt package manager (this also applies to other package managers such as yum/dnf and apk). The cache must be removed. For distributions using apt, the cache of installed programs is stored in the /var/lib/apt/lists directory. Therefore, we will add a command to delete all files in that directory within the RUN instruction without creating a new layer:

FROM debian:latest

COPY test.py .

RUN apt update && apt -y install python3 htop net-tools mc gcc && rm -rf /var/lib/apt/lists/*

CMD ["python3", "test.py"]

Build the image:

docker build -t python-optimize:03 .

And check the size:

Image7

The image size was reduced from the initial 570 MB to the current 551 MB.

Using Multi-Stage Builds

Another significant way to reduce the size of the created image is by using multi-stage builds. These builds, which involve two or more base images, allow us to separate the build environment from the runtime environment, effectively removing unnecessary files and dependencies from the final image. These unnecessary files might include libraries or development dependencies that are only needed during the build process.

Let’s explore this approach with a practical example using the Node.js platform. Node.js should be installed beforehand, following our guide.

We will first build the application image without multi-stage builds to evaluate the difference in size.

  1. Create a directory for the project:

mkdir node-app && cd node-app
  1. Initialize a new Node.js application:

npm init -y

Image12

  1. Install the express library:
npm install express
  1. Create an index.js file with the content:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

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

app.listen(PORT, () => {
  console.log(Server is running on port${PORT});
});
  1. Create Dockerfile with this content:
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY index.js .
EXPOSE 3000
CMD ["npm", "start"]
  1. Build the image:
docker build -t node-app:01 .

Image15

  1. Check the size:
docker images

Image19

  1. The image size was 124 MB. Now let's rewrite the Dockerfile to use two images, transforming it into the following form:
FROM node:14 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY index.js .

FROM gcr.io/distroless/base-debian10 AS production
WORKDIR /app
COPY --from=builder /app .
EXPOSE 3000
CMD ["npm", "start"]
  1. Build the image:
docker build -t node-app:02 .

Image18

  1. List the Docker images and check the size:
docker images

Image23

As a result, the image size was drastically reduced—from 124 MB to 21.5 MB.

Conclusion

In this article, we created our own Docker image and explored various ways to run it. We also paid significant attention to optimizing Docker images. Through optimization, we can greatly reduce the image size, which allows for faster image builds.

Docker
22.01.2025
Reading time: 12 min

Similar

Docker

Running Selenium with Chrome in Docker

Sometimes, it’s useful to work with Selenium in Python within a Docker container. This raises questions about the benefits of using such tools, version compatibility between ChromeDriver and Chromium, and the nuances of their implementation. In this article, we’ll cover key considerations and provide solutions to common issues. Why Run Selenium in Docker? Running Selenium in a container offers several advantages: Portability: Easily transfer the environment between different machines, avoiding version conflicts and OS-specific dependencies. Isolation: The Selenium container can be quickly replaced or updated without affecting other components on the server. CI/CD Compatibility: Dockerized Selenium fits well into CI/CD pipelines — you can spin up a clean test environment from scratch each time your system needs testing. Preparing an Ubuntu Server for Selenium with Docker First, make sure Docker and Docker Compose are installed on the server: docker --version && docker compose version In some Docker Compose versions, the command is docker-compose instead of docker compose. If the tools are installed, you’ll see output confirming their versions. If not, follow this guide. Selenium in Docker Example When deploying Selenium in Docker containers, consider the host architecture, functional requirements, and performance. Official selenium/standalone-* images are designed for AMD64 (x86_64) CPUs, while seleniarm/standalone-* images are adapted for ARM architectures (e.g., Apple silicon or ARM64 server CPUs). First, create a docker-compose.yml file in your project root. It will contain two services: version: "3" services: app: build: . restart: always volumes: - .:/app depends_on: - selenium platform: linux/amd64 selenium: image: selenium/standalone-chromium:latest # For AMD64 # image: seleniarm/standalone-chromium:latest # For ARM64 container_name: selenium-container restart: unless-stopped shm_size: 2g ports: - "4444:4444" # Selenium WebDriver API - "7900:7900" # VNC Viewer environment: - SE_NODE_MAX_SESSIONS=1 - SE_NODE_OVERRIDE_MAX_SESSIONS=true - SE_NODE_SESSION_TIMEOUT=300 - SE_NODE_GRID_URL=http://localhost:4444 - SE_NODE_DETECT_DRIVERS=false You must choose the correct image for your system architecture by uncommenting the appropriate line. The app service will run your main Python code. Let’s define a standard Dockerfile for this service: # Use a minimal Python image FROM python:3.11-slim # Set working directory WORKDIR /app # Install Python dependencies COPY requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # Copy project files COPY . /app/ # Set environment variables (Chromium is in a separate container) ENV SELENIUM_REMOTE_URL="http://selenium:4444/wd/hub" # Run Python script CMD ["python", "main.py"] This Dockerfile uses a base Python image and automatically installs the necessary dependencies. Now let’s add the driver initialization script to main.py: import time # Used to create a delay for checking browser functionality import os from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options # WebDriver settings chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-webrtc") chrome_options.add_argument("--hide-scrollbars") chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("--start-maximized") SELENIUM_REMOTE_URL = os.getenv("SELENIUM_REMOTE_URL", "http://selenium:4444/wd/hub") driver = webdriver.Remote( command_executor=SELENIUM_REMOTE_URL, options=chrome_options ) # Open a test page driver.get("https://www.timeweb.cloud") time.sleep(9999) # Shut down WebDriver driver.quit() In the requirements.txt file, list standard dependencies, including Selenium: attrs==25.1.0 certifi==2025.1.31 h11==0.14.0 idna==3.10 outcome==1.3.0.post0 PySocks==1.7.1 selenium==4.28.1 sniffio==1.3.1 sortedcontainers==2.4.0 trio==0.28.0 trio-websocket==0.11.1 typing_extensions==4.12.2 urllib3==2.3.0 websocket-client==1.8.0 wsproto==1.2.0 Now you can launch the containers: docker compose up -d Expected output: Docker will build and launch the containers. To verify everything is running correctly: docker compose ps You should see two running containers which means everything was loaded successfully. You can now integrate a script in main.py to interact with any site. Debugging Selenium in Docker with VNC In official Selenium Docker images (like seleniarm/standalone-chromium, selenium/standalone-chrome, etc.), direct access to the Chrome DevTools Protocol is usually overridden by Selenium Grid. It generates a new port for each session and proxies it via WebSocket. Arguments like --remote-debugging-port=9229 are ignored or overwritten by Selenium, making direct browser port access impossible from outside the container. Instead, these Docker images offer built-in VNC (Virtual Network Computing), similar to TeamViewer or AnyDesk, but working differently. VNC requires headless mode to be disabled, since it transmits the actual screen content — and if the screen is blank, there will be nothing to see. You can connect to the VNC web interface at: http://<server_ip>:7900 When connecting, you'll be asked for a password. To generate one, connect to the selenium-container via terminal: docker exec -it selenium-container bash Then enter: x11vnc -storepasswd You’ll be prompted to enter and confirm a password interactively. Enter the created password into the VNC web interface, and you’ll gain access to the browser controlled by Selenium inside Docker. From there, you can open DevTools to inspect DOM elements or debug network requests. Conclusion Running Selenium in Docker containers simplifies environment portability and reduces the risk of version conflicts between tools. It also allows visual debugging of tests via VNC, if needed. Just make sure to choose the correct image for your system architecture and disable headless mode when a graphical interface is required. This provides a more flexible and convenient infrastructure for testing and accelerates Selenium integration into CI/CD pipelines.
19 June 2025 · 5 min to read
Docker

Building Docker Images and Deploying Applications

Containerizing applications offers a convenient and flexible way to quickly deploy software, including web servers, databases, monitoring systems, and others. Containers are also widely used in microservices architectures. Docker is ideal for these purposes, as it greatly simplifies working with containerized apps. Introduced in 2013, Docker has seen continuous support and usage ever since. In this tutorial, you’ll learn how to create Docker images for three different applications written in different programming languages and how to run Docker containers from these images. Prerequisites To work with the Docker platform, you’ll need: A VPS or virtual machine with any Linux distribution preinstalled. In this tutorial, we use Ubuntu 22.04. Docker installed. You can find the Docker installation guide for Ubuntu 22.04 in our tutorials. Alternatively, you can use a prebuilt cloud server image with Docker — just select it in the “Marketplace” tab when creating a server. What Is a Docker Image? At the core of Docker’s concept is the image. A Docker image is a template—an executable file—you can use to start a Docker container. It contains everything needed to launch a ready-to-run application: source code, configuration files, third-party software, utilities, and libraries. Docker image architecture is layer-based. Each layer represents an action performed during the image build process, such as creating files and directories or installing software. Docker uses the OverlayFS file system, which merges multiple mount points into one, resulting in a unified directory structure. You can move Docker images between systems and use them in multiple locations, much like .exe executables in Windows systems. Creating Custom Docker Images Let’s walk through how to create Docker images for Flask, Node.js, and Go applications. Creating a Docker Image for a Flask Application To create images, a Dockerfile is used. Dockerfile is a plain text file without an extension that defines the steps to build a container image. You can find more details about Dockerfile instructions in the official documentation. We’ll create a Docker image with a web application built with Flask and run the container. The application will show a basic HTML page that displays the current date. 1. Install Required Packages Install the pip package manager and python3-venv for managing virtual environments: apt -y install python3-pip python3-venv 2. Create the Project Directory mkdir dockerfile-flask && cd dockerfile-flask 3. Create and Activate a Virtual Environment python -m venv env source env/bin/activate After activation, you'll see (env) in your prompt, indicating the virtual environment is active. Packages installed via pip will now only affect this environment. 4. Install Flask and Dependencies pip install flask pip install MarkupSafe==2.1.5 5. Create the Flask Application Create a file named app.py that will store the source code of our application: from flask import Flask import datetime app = Flask(__name__) @app.route('/') def display_current_date(): current_date = datetime.datetime.now().date() return f"Current date is: {current_date}" if __name__ == '__main__': app.run(debug=True) 6. Run and Test the Application flask run --host=0.0.0.0 --port=80 In your browser, visit your server’s IP address (port 80 doesn’t need to be specified as it’s the default one). You should see today’s date. 7. Freeze Dependencies Now, we need to save all the dependencies (just the flask package in our case) to a requirements.txt file, which stores all packages used in the project and installed via pip. pip freeze > requirements.txt Your project structure should now look like this: dockerfile-flask/ ├── app.py ├── env/ ├── requirements.txt Now we can proceed to creating a Docker image. 8. Create the Dockerfile Create a file named Dockerfile with the following contents: FROM python:3.8-slim-buster WORKDIR /app COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . CMD [ "python3", "-m", "flask", "run", "--host=0.0.0.0", "--port=80" ] Explanation: FROM python:3.8-slim-buster: Use Python 3.8 base image on a lightweight Debian Buster base. WORKDIR /app: Set the working directory inside the container (similar to the mkdir command in Linux systems) COPY requirements.txt requirements.txt: Copy the dependency list into the image. RUN pip3 install -r requirements.txt: The RUN directive runs the commands in the image. In this case, it’s used to install dependencies. COPY . .: Copy all project files into the container. CMD [...]: CMD defines the commands and app parameters to be used when the container starts. 9. Use a .dockerignore File Create a .dockerignore file to exclude unnecessary directories. It helps to decrease the image size. In our case, we have two directories that we don’t need to launch the app. Add them to the .dockerignore file: env __pycache__ 10. Build the Docker Image When building the image, we need to use a tag that would work as an identifier for the image. We’ll use the flask-app:01 tag. docker build -t flask-app:01 . The dot at the end means the Dockerfile is located in the same directory where we run the command. Check the created image: docker images 11. Run the Docker Container docker run -d -p 80:80 flask-app:01 -d: Run the container in the background. -p: Forward host port 80 to container port 80. Check running containers: docker ps The STATUS column should show “Up”.  Open your browser and navigate to your server's IP address to view the app. Creating a Docker Image for a Node.js Application Our simple Node.js app will display the message: “This app was created using Node.js!” Make sure you have Node.js installed on your system. 1. Create the Project Directory mkdir dockerfile-nodejs && cd dockerfile-nodejs 2. Initialize the Project npm init --yes 3. Install Express npm install express --save 4. Create the Application File Create app.js with the following code: const express = require("express"); const app = express(); app.get("/", function(req, res) { return res.send("This app was created using Node.js!"); }); app.listen(3000, '0.0.0.0', function(){ console.log('Listening on port 3000'); }); 5. Test the Application node app.js Open http://<your-server-ip>:3000 in a browser to verify it works. 6. Create the Dockerfile FROM node:20 WORKDIR /app COPY package.json /app RUN npm install COPY . /app CMD ["node", "app.js"] 7. Add .dockerignore Create .dockerignore and the following line: **/node_modules/ 8. Build the Image docker build -t nodejs-app:01 . 9. Start the Container from Image docker run -d -p 80:3000 nodejs-app:01 Visit http://<your-server-ip> in your browser. The app should be running. Creating a Docker Image for a Go Application This Go application will display: “Hello from GO!” Make sure you have Go installed in your system. 1. Create the Project Directory mkdir dockerfile-go && cd dockerfile-go 2. Initialize the Go Module go mod init go-test-app 3. Create the Application File Create main.go with this code of our application: package main import "fmt" func main() { fmt.Println("Hello from GO!") } Verify it works: go run . 4. Create the Dockerfile FROM golang:1.23-alpine WORKDIR /app COPY go.mod ./ RUN go mod download COPY *.go ./ RUN go build -o /go-test CMD [ "/go-test" ] COPY go.mod ./: Adds dependencies file. RUN go mod download: Installs dependencies. COPY *.go ./: Adds source code. RUN go build -o /go-test: Compiles the binary. 5. Build the Image docker build -t go:01 . 6. Run the Container docker run go:01 You should see the output: Hello from GO! Conclusion In this guide, we walked through building custom Docker images for three applications written in different programming languages. Docker allows you to package any application and deploy it with ease.
18 June 2025 · 7 min to read
Docker

How to Install Docker on MacOS

Docker is a platform that makes it easier to create, deploy, and operate applications in containers. Containers enable developers to bundle an application's dependencies, including as libraries, frameworks, and runtime environments, and ship it as a single package. This ensures that the program runs reliably and consistently, independent of the environment in which it is deployed. If you have troubles with that, here's our instruction how to deploy server with Docker. Docker allows you to automate the deployment of software inside lightweight, portable containers. These containers may operate on any system with Docker installed, making it simple to deploy apps across several settings, such as a developer's laptop, a testing server, or a production environment on the cloud. Docker also includes tools for managing and orchestrating containers at scale, making it simpler to deploy, scale, and manage complex applications in production environments. Below are the requirements to prepare for the installation of docker on MacOS:  A supported version of MacOS. Docker Desktop is compatible with the latest macOS versions. This includes the current macOS release as well as the two previous releases. As new major versions of macOS become widely available, Docker stops supporting the oldest version and instead supports the most recent version (along with the prior two). RAM: minimum of 4 GB. This is to optimize Docker performance especially when operating multiple containers.  In installing docker, you can either install it interactively or manually or via the command line interface. Here’s the guide on how to do the installation with both methods. Manual Installation Download the installer from the official docker website using the following links: Apple Silicon processor Intel chip processor Install Docker Desktop by double-clicking the Docker.dmg:  And drag and drop it to the Application folder. By default, the Docker Desktop is installed at /Applications/Docker. Wait for the copying to finish. Double-click the Docker from the Applications folder to proceed with the installation. Click Accept to continue in the Docker Subscription Service Agreement page. From the installation window, choose either: Use recommended settings (Requires password) Use advanced settings Click Finish.  Verify if installation is successful. A Docker icon should appear on the menu bar when the Docker Desktop is installed and running. A notification will appear stating that Docker is running. Install using Command Line Interface Once Docker.dmg is downloaded from the official docker website, login as a super user / root in a terminal to install Docker Desktop in the Application folder. Execute the below commands respectively.  hdiutil attach Docker.dmg /Volumes/Docker/Docker.app/Contents/MacOS/install hdiutil detach /Volumes/Docker If running as a normal user, execute the command with sudo: sudo hdiutil attach Docker.dmg sudo /Volumes/Docker/Docker.app/Contents/MacOS/install sudo hdiutil detach /Volumes/Docker Installation might take some time to complete since the system may do various security checks while installing Docker on Mac. Troubleshooting Some of the common issues that the user might encounter during the installation of MacOS are:  Users may not check the MacOs version of their machine. Take note of the system requirements when installing Docker on MacOS to avoid installation failure and unexpected behavior (like docker image becomes corrupted). Errors during the installation process may occur such as failed downloads, incomplete installation, etc. Go back and check the system and hardware compatibility of the machine.  Conflict with existing software. This requires troubleshooting and investigating system logs. Usually, this can be solved by removing the problematic software.  Permission and security issues. When installing Docker on MacOS, ensure that the machine has all the required permission to access system resources, like directory, network, etc.  Conclusion To summarize, installing Docker on MacOS provides various opportunities for both developers and system administrators. Docker technology provides resources with an enhanced development workflow, an efficient procedure for delivering apps, and consistent system environments. Embrace containerization to broaden your development horizons. Check what Hostman VPS Servers can give you.
30 April 2025 · 4 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support