Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 111 ยท Dockerfiles

docker init and Generated Project Files

Use docker init to scaffold a Dockerfile, compose.yaml, .dockerignore and README for your project, understand what each generated file does and how to adapt it.

Writing your first Dockerfile from a blank page is the part of Docker where beginners get stuck, and experienced people still forget small details such as a .dockerignore, a non-root user or a cache mount. docker init is a built-in command that asks a few questions about your project and writes a starter set of Docker files that already follow current best practices. You then read them, adjust them and commit them.

This lesson explains what docker init creates, which questions it asks, how to read the generated files so that you can change them with confidence, and when it is better to write the files yourself. docker init is an interactive wizard, so it needs a real terminal. That is why the sessions below are read-only examples: the file contents are abridged and differ a little between versions of the command (this lesson was written against docker init v1.4). Use them to know what to expect, not as text to copy.

What the command does

Run it in the root folder of an existing project:

CONSOLE
$ cd my-project
$ docker init --version
Version:    v1.4.0

docker init has almost no flags. It is a guided wizard: it looks at the files in the folder, guesses the language, asks you to confirm, and writes four files.

File Purpose
Dockerfile Recipe to build an image of your app (usually multi-stage, with a non-root user)
compose.yaml A Compose file that builds that Dockerfile, publishes the port and has commented examples for a database
.dockerignore Keeps .git, virtual environments, node_modules, logs and local config out of the build context
README.Docker.md Short instructions for the people who will run the project: how to start it and how to deploy it

If any of those files already exist, the wizard asks before overwriting each one, so running it in an old project is safe. Still, commit your work first so that git diff shows exactly what changed.

flowchart LR
    A["Your project folder"] --> B["docker init"]
    B --> C["Detects language<br/>from files"]
    C --> D["Asks: platform, version,<br/>port, run command"]
    D --> E["Dockerfile"]
    D --> F["compose.yaml"]
    D --> G[".dockerignore"]
    D --> H["README.Docker.md"]

docker init inspects the folder, confirms a few answers with you, and writes four files.

The wizard, step by step

The supported application platforms are Go, Python, Node, Rust, ASP.NET Core, PHP with Apache, Java and a generic "Other" option. The generic option writes a minimal Dockerfile and Compose file without a language template, which is useful when your stack is not on the list.

A session for a small Python project that has an app.py and a requirements.txt looks like this (the ? lines are questions, the text after them is the proposed default or your answer):

TEXT
Welcome to the Docker Init CLI!

This utility will walk you through creating the following files with sensible defaults for your project:
  - .dockerignore
  - Dockerfile
  - compose.yaml
  - README.Docker.md

Let's get started!

? What application platform does your project use? Python
? What version of Python do you want to use? 3.13
? What port do you want your app to listen on? 8000
? What is the command you use to run your app? python3 -m flask run --host=0.0.0.0

CREATED: .dockerignore
CREATED: Dockerfile
CREATED: compose.yaml
CREATED: README.Docker.md

โœ” Your Docker files are ready!

Each question maps directly to a line you can find in the output:

  • Version becomes an ARG (for example ARG PYTHON_VERSION=3.13) used in FROM, so upgrading the runtime later means changing one number.
  • Port becomes EXPOSE in the Dockerfile and the ports: mapping in compose.yaml.
  • Run command becomes the CMD of the image.

Other languages ask different things. Node asks for the package manager (npm, yarn or pnpm) and a build script. Go asks for the relative path of the main package. Java asks for the source folder and Java version. The ASP.NET template asks for the project and .NET version. Whatever the platform, the answers are small and easy to change afterwards, because they are only text in files.

Reading the generated Dockerfile

Here is an abridged version of what the Python template produces. The exact lines differ per version, but the ideas stay the same:

DOCKERFILE
# syntax=docker/dockerfile:1

ARG PYTHON_VERSION=3.13
FROM python:${PYTHON_VERSION}-slim AS base

# Do not write .pyc files; do not buffer stdout/stderr.
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

WORKDIR /app

# Create a non-privileged user to run the app.
ARG UID=10001
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    appuser

# Cache pip downloads between builds; bind-mount requirements so a
# change to the source code does not invalidate this layer.
RUN --mount=type=cache,target=/root/.cache/pip \
    --mount=type=bind,source=requirements.txt,target=requirements.txt \
    python -m pip install -r requirements.txt

USER appuser

COPY . .

EXPOSE 8000

CMD python3 -m flask run --host=0.0.0.0

Compare it with what you learned earlier in this course. Nearly every line is a practice you already know:

  • # syntax=docker/dockerfile:1 pins the Dockerfile frontend, so newer features such as --mount work (see BuildKit and buildx).
  • A version ARG and a -slim base follow Choosing Base Images.
  • WORKDIR, USER and EXPOSE appear in WORKDIR, USER and EXPOSE. The numeric user id (10001) is the reason docker init images run as non-root by default; see Users and Permissions.
  • The cache mount keeps pip's download cache outside the image layers, and the bind mount of requirements.txt means the dependency layer only rebuilds when that file changes. This is the technique from Build Cache written in BuildKit style.
  • The dependency install happens before COPY . ., so editing source files does not reinstall packages.

The Go, Rust and Java templates use multi-stage builds: one stage compiles, a final stage copies only the result into a small image. That is the pattern from Multi-Stage Builds.

Treat the generated Dockerfile as a very good first draft, not as a finished product. Read every line once. If you cannot explain a line, look it up in the lessons of this chapter before you ship it.

The generated compose.yaml

The Compose file is intentionally short. In the Python example it looks like this:

YAML
services:
  server:
    build:
      context: .
    ports:
      - 8000:8000

# The commented-out section below is an example of how to define a PostgreSQL
# database that your application can use. `depends_on` tells Docker Compose to
# start the database before your application. The `db-data` volume persists the
# database data between container restarts. The `db-password` secret is used
# to set the database password. You must create `db/password.txt` and add
# a password of your choosing to it before running `docker compose up`.
#     depends_on:
#       db:
#         condition: service_healthy
#   db:
#     image: postgres
#     restart: always
#     user: postgres
#     secrets:
#       - db-password
#     volumes:
#       - db-data:/var/lib/postgresql/data
#     environment:
#       - POSTGRES_DB=example
#       - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
#     expose:
#       - 5432
#     healthcheck:
#       test: [ "CMD", "pg_isready" ]
#       interval: 10s
#       timeout: 5s
#       retries: 5

The active part is only eight lines: one service named server, built from the current folder, publishing the port you chose. The commented-out part is a worked example of a database service with a named volume, a Compose secret and a health check. Uncomment it when your project needs a database, and compare it with Compose: Dependencies and Health Checks and Secrets Management. Start the project as usual:

CONSOLE
$ docker compose up --build

The generated .dockerignore

The ignore file is the least glamorous output and one of the most useful. A typical Python one starts like this:

TEXT
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
**/__pycache__
**/.venv
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/compose*.yaml
**/Dockerfile*
**/node_modules
**/npm-debug.log
README.md

It keeps secrets in .env files, the .git history and heavyweight folders out of your build context, which makes builds faster and prevents accidents like baking credentials into a layer. The build context and .dockerignore explains why this matters. Add your own project-specific folders (test data, IDE settings, build output) to the list.

Adapting the output to your project

After running the wizard, a short checklist turns the draft into your Dockerfile:

  1. Run it once. docker compose up --build should start your app. If not, the usual suspects are a wrong run command (answer typed with a typo) or an app that listens on 127.0.0.1 instead of 0.0.0.0; see Networking Troubleshooting.
  2. Pin versions deliberately. The ARG keeps the language version in one place. Consider pinning the base image by tag and digest when reproducibility matters (Image Tagging Strategy).
  3. Add a health check if the service has an HTTP endpoint (HEALTHCHECK).
  4. Add a test stage or a dev target if you want one image for CI and another for production.
  5. Delete what you do not need. The commented database block is helpful once and noise afterwards.
  6. Commit all four files and review git diff when you rerun the wizard after a big change.

When not to use it

docker init shines for conventional single-service projects. Write the files by hand when:

  • You have a monorepo with several services that share one build context.
  • Your language or framework is not in the list and the generic template saves you nothing.
  • You need unusual build steps (code generation, private package registries, custom toolchains).
  • You already have a well-tuned Dockerfile in the team, which is better than any template.

Even then, running docker init in an empty scratch folder is a good way to see how Docker's authors currently write a Dockerfile for a language you do not know well.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which files does docker init write?

    docker init scaffolds four text files. It does not build or push anything; you review and run the files yourself.
  2. 2. Why do the generated Dockerfiles install dependencies before running COPY . . ?

    Layers are cached in order. Dependencies change rarely and source files change often, so the dependency layer comes first and stays cached.
  3. 3. What should you do before relying on the generated files?

    The output is a good first draft built from general assumptions. Review it, test it and adapt it to your app.
  4. 4. The wizard finds an existing Dockerfile in the folder. What happens?

    docker init prompts before overwriting existing files, but committing first is still wise so you can compare.

Summary

  • docker init is an interactive wizard that writes a Dockerfile, compose.yaml, .dockerignore and README.Docker.md for a detected language (Go, Python, Node, Rust, ASP.NET Core, PHP, Java or Other).
  • Your answers (language version, port, run command) become an ARG, EXPOSE/ports: and CMD.
  • The templates apply good practice: non-root user, cache and bind mounts for dependencies, multi-stage builds for compiled languages, a thorough ignore list.
  • The Compose file is short and includes a commented database example you can enable.
  • Always review and test the output, then adapt it. For monorepos or unusual builds, write the files by hand.

Next: docker buildx bake