Creating a Dockerfile
Before getting started, you'll need:
- Docker Desktop installed
- An IDE (like VS Code)
Creating needed files
This guide will walk you through the process of creating a basic Dockerfile for your application. First, let's create 2 files in your application's directory:
Dockerfile is a list of step by step instructions for the container at startup so that it can run your application. The
.dockerignore file will allow you to set certain files or directories for your
Dockerfile to ignore.
Let's get started with a basic
Dockerfile. We'll use Python.
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
CMD ["python3", "-m" , "flask", "run", "--host=0.0.0.0"]
Now let's break down each section:
FROM python:3.8-slim-buster: This line is telling the
Dockerfilewhere to download a base image from. The base image also has its own set of step by step instructions, and will also download the tools and packages needed to run my Python application.
WORKDIR /app: We want to set a working directory within the container for my application. This tells Docker to use
/appwithin the container as the default path for all subsequent commands.
COPY requirements.txt requirements.txt: We're telling the container to
requirements.txtfile and then I tell Docker where to put it. In this case, we are copying the file to
RUN pip3 install -r requirements.txt: Now we're instructing the container to
pip3 installfor all of my Python app dependencies listed in my
COPY . .: Now that we have the Python base image installed, and all of my Python app dependencies, we now want to copy the source code into the image. We're saying
COPYall files here
/app(excluding any files/directories listed in my
EXPOSE 8080: This command exposes the internal container port of
8080so that the runtime running the container can access the image.
CMD ["python3", "-m" , "flask", "run", "--host=0.0.0.0"]: Finally, we're telling Docker to run a specific command using
CMD. We're also making the application visible outside of the container using
Your directory structure should now look similar to this:
These are the basic components of a
Dockerfile. For a more specific template for your desired language, check out templates