Hakia LogoHAKIA.com

How to Create Your First Docker Container Step-by-Step

Author

Taylor

Date Published

Illustration depicting Docker containers being built or stacked, symbolizing the container creation process.

Getting Started with Docker: Your First Container

If you're involved in software development or just curious about modern technology, you've probably heard about Docker. It's a tool that has become incredibly popular for building, shipping, and running applications. But what exactly is it, and how can you start using it? This guide will walk you through the process of creating your very first Docker container, step by step, using straightforward language.

What is Docker?

Think of Docker as a way to package software—your application, along with all the things it needs to run, like code libraries, system tools, and settings—into a single unit called a container. This container can then run consistently on almost any computer, anywhere.

Unlike traditional virtual machines (VMs) that bundle a whole operating system, Docker containers share the host computer's operating system kernel. This makes them much lighter and faster to start. The main benefit? If your application runs in a container on your laptop, you can be pretty confident it will run the same way on a testing server, a production server, or another developer's machine. This solves the classic problem of "it works on my machine!"

Why Use Docker?

Using Docker offers several advantages:

  • Consistency: Ensures your application runs the same way everywhere.
  • Speed: Containers start and stop quickly.
  • Isolation: Keeps applications and their dependencies separate, avoiding conflicts.
  • Efficiency: Containers use fewer resources (CPU, RAM) than VMs.
  • Simplified Setup: Setting up complex development environments becomes much easier.

Before You Start: Prerequisites

To follow this guide, you'll need a couple of things:

  • Docker Installed: You need Docker running on your computer. The easiest way for Windows and macOS users is to install Docker Desktop from the official Docker website. Linux users can typically install Docker Engine using their distribution's package manager.
  • Command Line Access: You'll be using the terminal (on macOS/Linux) or Command Prompt/PowerShell (on Windows) to run Docker commands.
  • Text Editor: Any simple text editor (like VS Code, Sublime Text, Notepad++, or even Notepad) will work for creating the necessary files.

Once Docker is installed, open your terminal or command prompt and run `docker --version`. You should see the installed Docker version, confirming it's ready to go.

Core Docker Concepts: Images and Containers

Before we build, let's clarify two fundamental concepts:

  • Docker Image: This is a template or blueprint containing instructions for creating a container. It includes the application code, libraries, dependencies, and configuration. Images are often built based on other images (e.g., an official Python image). You can find many pre-built images on Docker Hub.
  • Docker Container: This is a runnable instance of an image. When you run an image, you create a container. You can have many containers running from the same image, each isolated from the others and the host machine.

To build our own image, we use a special file called a Dockerfile.

Step-by-Step: Creating Your First Container

Let's create a very simple container that runs a Python script to print a message. You don't even need Python installed on your computer for this to work – Docker will handle it!

Step 1: Set Up Your Project Directory

First, create a new folder for your project. Let's call it `my-docker-app`. Open your terminal or command prompt and navigate into this new folder.

Inside `my-docker-app`, create two files:

  • app.py: This will be our simple Python script.
  • Dockerfile: This file (with no extension) tells Docker how to build the image.

Open `app.py` in your text editor and add this single line of code:

print("Hello from inside the Docker container!")

Save the file. Leave the `Dockerfile` empty for now.

Step 2: Write the Dockerfile

Now, open the `Dockerfile` in your text editor. This file contains instructions, one per line, for Docker to follow when building the image. Add the following lines:

# Use an official Python runtime as a parent image FROM python:3.9-slim # Set the working directory in the container WORKDIR /app # Copy the current directory contents into the container at /app COPY . . # Run app.py when the container launches CMD ["python", "./app.py"]

Let's break down what these instructions mean:

  • FROM python:3.9-slim: This tells Docker to use the official Python 3.9 image (specifically the `slim` version, which is smaller) as the starting point or base for our image.
  • WORKDIR /app: This sets the working directory inside the container to `/app`. Subsequent commands like `COPY` and `CMD` will run relative to this directory.
  • COPY . .: This copies files from the current directory on your host machine (where the `Dockerfile` is, indicated by the first `.`) into the container's working directory (`/app`, indicated by the second `.`). So, `app.py` gets copied into `/app` inside the container.
  • CMD ["python", "./app.py"]: This specifies the command that should be executed when a container starts from this image. Here, it tells the container to run the command `python ./app.py`.

Save the `Dockerfile`.

Step 3: Build the Docker Image

Now that we have the `Dockerfile`, we can build the image. Make sure you are still in the `my-docker-app` directory in your terminal. Run the following command:

docker build -t my-first-app .

Let's understand this command:

  • docker build: The command to build an image from a Dockerfile.
  • -t my-first-app: The `-t` flag stands for 'tag'. It allows you to give your image a memorable name (in this case, `my-first-app`). Naming images makes them easier to manage and run.
  • .: The dot at the end tells Docker to look for the `Dockerfile` in the current directory (the 'build context').

Docker will now execute the steps in your `Dockerfile`. If this is the first time you're using the `python:3.9-slim` image, Docker will download it first. You'll see output in your terminal showing each step being processed. Once it finishes, you've successfully built your first Docker image!

You can see the image you just created by running:

docker image ls

You should see `my-first-app` listed in the output.

Step 4: Run the Docker Container

With the image built, you can now run it to create a container. Use the following command:

docker run my-first-app

What happens here?

  • Docker takes the `my-first-app` image.
  • It creates a new container based on that image.
  • It runs the command specified in the `CMD` instruction of the Dockerfile (`python ./app.py`).

You should see the following output printed directly in your terminal:

Hello from inside the Docker container!

Congratulations! You just created and ran your first Docker container. Since the Python script just prints a message and exits, the container stops immediately after executing the command.

Running a Container with a Web Server

The previous example was simple. Often, you'll want to run applications that keep running, like web servers. Let's imagine you have a Node.js web application image named `my-web-app` that listens on port 3000 inside the container. To run it and access it from your browser, you'd use a command like this:

docker run -d -p 8080:3000 my-web-app

Here's what the new flags do:

  • -d: Stands for 'detached' mode. It runs the container in the background and prints the container ID, so your terminal is free.
  • -p 8080:3000: Stands for 'publish'. It maps port 8080 on your host machine to port 3000 inside the container. This allows you to access the application running inside the container by going to `http://localhost:8080` in your web browser.

This ability to package and run web applications is a primary reason Docker is so widely used. You can follow a more detailed walkthrough for containerizing a sample application in the official Docker documentation.

Basic Docker Commands for Management

As you work with Docker, you'll use a few commands regularly:

  • docker ps: List currently running containers.
  • docker ps -a: List all containers, including stopped ones.
  • docker stop <container_id_or_name>: Stop a running container.
  • docker rm <container_id_or_name>: Remove a stopped container.
  • docker image ls: List the images stored locally on your machine.
  • docker image rm <image_id_or_name>: Remove an image from your local machine.

You can find more helpful commands and examples in this beginner's guide to Docker.

Next Steps

You've successfully created and run your first Docker container! This is just the starting point. From here, you can explore more advanced topics:

  • Docker Compose: A tool for defining and running multi-container Docker applications (e.g., a web application connected to a database).
  • Volumes: For persisting data generated by and used by Docker containers.
  • Networking: Connecting containers together and to the outside world.
  • Docker Hub: A registry service where you can find official images and share your own. Learn how to build and push your first image to share your work.

Understanding Docker and containers is becoming essential for software developers and operations teams. This process of packaging applications, known as containerization, is one of the key modern application packaging techniques. By mastering these basics, you've taken a significant step towards streamlining how you build and deploy software. If you want to explore more tech topics, you can find additional resources and articles.

Sources

https://www.freecodecamp.org/news/a-beginners-guide-to-docker-how-to-create-your-first-docker-application-cc03de9b639f/
https://docs.docker.com/get-started/workshop/02_our_app/
https://docs.docker.com/get-started/introduction/build-and-push-first-image/
https://hakia.com
https://hakia.com/posts/containerization

Abstract visualization representing the future evolution of containerization technology beyond traditional containers.
Containerization

Explore the future of containerization beyond Docker and Kubernetes. Discover key trends like WebAssembly, serverless computing, unikernels, enhanced security, and edge applications shaping software deployment.