DevFox Labs
HomeCoursesRoadmapsChallengesToolsAboutContact
beginner30 minby DevFoxUpdated on 1 Aug 2026

Writing Your First Dockerfile

Build your own image from a text file: FROM, WORKDIR, COPY, RUN and CMD, each introduced by the problem it solves, ending with an application you built and ran yourself.

  • Docker
Writing Your First Dockerfile. Read this lesson at .

Previous lesson · 3 of 13Images, Containers and the DifferenceNext lesson · 5 of 13Layers, Caching and Build Context

On this page

  • Why a file and not a set of commands
  • The application we will package
  • Your first Dockerfile
  • Reading the instructions one at a time
  • Building it
  • Running your own image
  • Tagging as you go
  • CMD, ENTRYPOINT and the confusion
  • The mistake everyone makes once
  • Cheat sheet
  • Where to go next
DevFox Labs

Structured lessons and courses for developers who care about craft.

Platform

HomeCoursesRoadmapsAll lessonsChallengesAboutContactRSS feed

Legal

Terms of ServicePrivacy PolicyCookie Policy

© 2026 DevFox Labs. All rights reserved.

    Everything you have run so far belonged to somebody else. That is fine for a web server or a database, but the reason you are learning this is your own code — and your code is not on Docker Hub.

    This is the lesson that closes the gap. By the end of it you will have written a Dockerfile, built an image from it, and run your own application in a container you made. It is the moment Docker stops being a way to borrow software and becomes a way to ship yours.

    Why a file and not a set of commands

    You could build an image the manual way. Start a plain Ubuntu container, install a runtime, copy files in, and freeze the result with docker commit. It works, and nobody does it, for the same reason nobody documents deployment as a list of chat messages: a sequence of actions somebody performed once cannot be reviewed, diffed, repeated or fixed.

    A Dockerfile is those steps written down as a text file that lives next to your code, in version control, where a change to the environment shows up in a pull request like any other change.

    That is the real shift. Your environment stops being something a person did to a machine and becomes something the repository describes.

    The application we will package

    We need something real to containerise. Here is a small Python web service — three files, no framework magic, and it does something you can see in a browser.

    Create a directory and put this in app.py:

    python
    from flask import Flask
    import os
    
    app = Flask(__name__)
    
    
    @app.get("/")
    def index():
        name = os.environ.get("GREET_NAME", "world")
        return f"Hello, {name}!\n"
    
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0", port=8000)

    And this in requirements.txt:

    text
    flask==3.0.3

    Two files. On your own machine you would create a virtual environment, install Flask into it, and run python app.py. Instead, we are going to describe that whole process to Docker.

    Why host is 0.0.0.0 and not localhost

    Inside a container, 127.0.0.1 means "only this container", so a server bound to it cannot be reached from outside no matter what ports you publish. Binding to 0.0.0.0 means "every interface in here", which is what makes the container reachable. The networking lesson goes into this properly.

    Your first Dockerfile

    Create a file named exactly Dockerfile, with no extension, next to app.py:

    Nine lines, and every one of them answers a question you would otherwise have to answer by hand. Read it as a recipe: start from this, work here, bring these files, run this to prepare, and this is what to do when you start.

    Reading the instructions one at a time

    FROM python:3.12-slim — every image starts from another image, and this one says which. You are not building an operating system from nothing; you are starting from a filesystem that already has Python 3.12 installed and adding to it. The -slim variant drops documentation, build tools and extras you rarely need, which takes the base from around 1 GB to about 130 MB.

    WORKDIR /app — sets the working directory inside the image, creating it if needed. Every later COPY, RUN and CMD runs relative to it, so you write COPY app.py . instead of repeating the path everywhere. It is also where you land when you docker exec into the container, which makes debugging pleasanter.

    COPY requirements.txt . — copies a file from your machine into the image. The first path is on your machine, relative to where you run the build; the second is inside the image. Files do not arrive in an image by accident — if you did not copy it, it is not there.

    RUN pip install --no-cache-dir -r requirements.txt — runs a command while building, and whatever it changes becomes part of the image. This is the line that installs Flask. --no-cache-dir stops pip keeping its download cache, which would otherwise be baked into the image as dead weight you can never use.

    COPY app.py . — brings in the application code, after the dependencies. That ordering is deliberate and pays for itself enormously; the next lesson explains exactly why.

    EXPOSE 8000 — documents which port the program inside listens on. It publishes nothing on its own; it is a note for humans and for tools. You still need -p when you run.

    CMD ["python", "app.py"] — what to run when a container starts. Nothing in the image executes at build time except your RUN lines; CMD is the default command for the finished image.

    Always use the bracket form

    CMD ["python", "app.py"] runs your program directly. CMD python app.py wraps it in a shell, and the shell becomes the process that receives shutdown signals — so your program never hears docker stop and gets killed ten seconds later instead of exiting cleanly.

    Building it

    From the directory containing the Dockerfile:

    Two parts matter. -t hello-docker tags the resulting image with a name you can use later. The . at the end is the build context: the directory Docker sends to the daemon so that COPY has something to copy from. It is easy to read as punctuation, but it is an argument, and leaving it off is an error.

    The output narrates each instruction:

    Confirm it exists:

    Running your own image

    It is an image like any other, so you already know this command:

    Visit http://localhost:8000 and your application answers. Then prove the environment travelled with it:

    Visit http://localhost:8001 and the greeting has changed. One image, two different behaviours, no rebuild — which is the whole point of reading configuration from the environment, and the subject of a later lesson.

    Nothing about Flask or Python 3.12 was installed on your machine. Delete the image and there is no trace left.

    Tagging as you go

    docker build -t hello-docker . gave you hello-docker:latest, because a tag with no version defaults to latest. Once an image matters to anyone but you, say which version it is:

    The second form applies both tags to the same image in one build — a specific version to depend on, and a moving latest for convenience.

    CMD, ENTRYPOINT and the confusion

    Both say what runs when the container starts, and the difference is what happens when someone passes arguments to docker run.

    CMD

    A default that gets replaced.

    docker run hello-docker runs python app.py.

    docker run hello-docker python -V runs python -V — your CMD is gone entirely.

    ENTRYPOINT

    Fixed. Arguments are appended.

    docker run hello-docker --debug runs python app.py --debug.

    The image behaves like the tool it wraps, rather than like a box you can run anything inside.

    Same image, same instruction text, opposite behaviour when an argument is passed

    Used together, ENTRYPOINT is the command and CMD supplies its default arguments:

    For a single-purpose application image, CMD alone is the right default. Reach for ENTRYPOINT when your image is a wrapper around one tool and you want it to behave like that tool.

    Which one your base image already has

    Many official images set an ENTRYPOINT of their own — which is why docker run postgres --help prints Postgres help rather than starting a database. Check with docker inspect before assuming your CMD is the whole story.

    The mistake everyone makes once

    Bad — the container exits immediately with no error at all:

    Good — the same image, with the last line as the container's command:

    The whole of the difference is when each one runs.

    1. 1

      FROM, WORKDIR, COPY, RUN — during the build

      Each one produces a layer. RUN pip install belongs here, because installing should happen once and be frozen into the image.

    2. 2

      The image now exists and nothing is running

      It is a snapshot on disk. docker build has finished.

    3. 3

      CMD — when a container starts

      Once per container, every time. This is where your server belongs.

    Everything above the line happens once, at build time. Only the last step happens per container.

    Put the server in RUN and it starts while building, hangs until the build times out or you interrupt it, and leaves you an image whose default command is whatever the base image had — so the container starts, finds nothing to do, and exits with status 0 and an empty log.

    Cheat sheet

    Where to go next

    Build the same image a second time and notice how much faster it is. That speed is the build cache, and understanding it is the difference between a five-second rebuild and a five-minute one — which is the next lesson, along with why COPY requirements.txt came before COPY app.py.

    After that come volumes, so the data your container writes can survive it, and networking, so two containers can talk. For now, containerise something of your own: any script or small service you already have. The first Dockerfile you write for real code teaches more than reading three more lessons about it.

    text
    [+] Building 12.4s (10/10) FINISHED
     => [internal] load build definition from Dockerfile      0.0s
     => [internal] load metadata for docker.io/library/pyt…   1.2s
     => [1/5] FROM docker.io/library/python:3.12-slim        4.1s
     => [2/5] WORKDIR /app                                   0.1s
     => [3/5] COPY requirements.txt .                        0.0s
     => [4/5] RUN pip install --no-cache-dir -r requireme…   6.3s
     => [5/5] COPY app.py .                                  0.0s
     => exporting to image                                   0.4s
     => => naming to docker.io/library/hello-docker:latest   0.0s
    text
    REPOSITORY     TAG      IMAGE ID       CREATED          SIZE
    hello-docker   latest   7f2a91c4e8b3   9 seconds ago    143MB
    bash
    docker build -t hello-docker .
    bash
    docker images hello-docker
    bash
    docker run -d -p 8000:8000 --name hello hello-docker
    bash
    docker run --rm -e GREET_NAME=Antonii -p 8001:8000 hello-docker
    bash
    docker build -t hello-docker:0.1.0 .
    docker build -t hello-docker:0.1.0 -t hello-docker:latest .
    bash
    # Building and running your own image
    docker build -t hello-docker .              # build from ./Dockerfile
    docker build -t hello-docker:0.1.0 .        # ...with a version tag
    docker build -f api.Dockerfile -t api .     # a differently named file
    docker build --no-cache -t hello-docker .   # ignore cached layers
    
    docker images hello-docker                  # confirm it was built
    docker run -d -p 8000:8000 hello-docker     # run it
    docker run --rm -e GREET_NAME=you hello-docker   # override config
    docker exec -it hello sh                    # look inside it
    docker logs hello                           # read its output
    dockerfile
    FROM python:3.12-slim
    
    WORKDIR /app
    
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY app.py .
    
    EXPOSE 8000
    
    CMD ["python", "app.py"]
    dockerfile
    ENTRYPOINT ["python", "app.py"]
    CMD ["--port", "8000"]
    dockerfile
    FROM python:3.12-slim
    WORKDIR /app
    COPY . .
    RUN pip install --no-cache-dir -r requirements.txt
    RUN python app.py
    dockerfile
    FROM python:3.12-slim
    WORKDIR /app
    COPY . .
    RUN pip install --no-cache-dir -r requirements.txt
    CMD ["python", "app.py"]
    dockerfile
    # Dockerfile instructions used in this lesson
    FROM python:3.12-slim         # the image to build on top of
    WORKDIR /app                  # working dir for later instructions
    COPY requirements.txt .       # host path -> image path
    RUN pip install -r req.txt    # run at BUILD time, result is a layer
    EXPOSE 8000                   # document the port (publishes nothing)
    ENV GREET_NAME=world          # a default environment variable
    CMD ["python", "app.py"]      # default command, replaceable
    ENTRYPOINT ["python", "app.py"]   # fixed cmd, args appended