How to Use the docker init Command: Automatically Generate Best-Practice Dockerfiles and Compose Files

Docker tutorial - IT technology blog
Docker tutorial - IT technology blog

Quick Start: Initialize Docker Configs in Minutes

What is your go-to process whenever you need to containerize a new repo? Dig through an old project, copy over a Dockerfile, and spend time tweaking ports and commands? This approach is not only time-consuming but also prone to carrying over outdated configurations. Starting with Docker Desktop 4.18 (Docker CLI v23.0), Docker introduced the built-in docker init command to handle this tedious step automatically.

Navigate to your project’s root directory and run a single command:

cd /path/to/my-project
docker init

An interactive CLI wizard will appear in your terminal, asking a few questions about your tech stack:

? What application platform does your project use?  [Use arrows to move, type to filter]
  Go
> Node
  Python
  Rust
  ASP.NET Core
  Java
  Other

The wizard will walk you through five key questions:

  1. Application platform: Your project’s language or runtime (Node, Python, Go, Java, Rust…).
  2. Version: The runtime version (such as Node 20.11 or Python 3.11).
  3. Package manager: Your package manager (npm, yarn, or pnpm).
  4. Entrypoint command: The command to start your application (npm start, python manage.py runserver, or uvicorn main:app).
  5. Port: The port your service listens on (e.g., 3000, 8000).

After answering these prompts in about 30 seconds, Docker generates four files in your root directory:

  • Dockerfile: Pre-configured with multi-stage builds, cache mounts, and a non-root user.
  • compose.yaml: A Compose file pre-configured with port mappings, environment variables, and volumes.
  • .dockerignore: Ignores unwanted files such as node_modules, .git, build artifacts, and logs.
  • README.Docker.md: A practical cheat sheet detailing how to build, run, and debug your service.

Now spin up your container stack:

docker compose up --build -d
docker compose logs -f

Your application is now running cleanly inside a container. The entire process takes under two minutes without writing a single line of boilerplate from scratch.

What’s Inside the Files Generated by docker init?

Convenience is just the start. The real value of docker init lies in how strictly it adheres to best practices that developers often overlook when writing configurations manually.

1. Dockerfile: Optimized Caching and Hardened Security

Here is an example Dockerfile generated for a Node.js project:

# syntax=docker/dockerfile:1

ARG NODE_VERSION=20.11.0
FROM node:${NODE_VERSION}-alpine as base
WORKDIR /usr/src/app
EXPOSE 3000

FROM base as deps
RUN --mount=type=bind,source=package.json,target=package.json \
    --mount=type=cache,target=/root/.npm \
    npm ci --omit=dev

FROM deps as final
USER node
COPY package.json .
COPY --from=deps /usr/src/app/node_modules ./node_modules
COPY . .
CMD npm start

Three critical technical highlights stand out:

  • BuildKit Cache Mount (--mount=type=cache): Caches npm/pip packages directly in the host engine. If you modify a line of JavaScript code, Docker doesn’t need to re-download dependencies from scratch, slashing build times from minutes down to seconds.
  • Non-root user (USER node): The process runs without root privileges. Even if the application suffers from a Remote Code Execution (RCE) vulnerability, attackers cannot easily escalate privileges to compromise the host system.
  • Alpine base image: Uses a lightweight base image (~50MB) instead of pulling heavy 800MB–1GB Ubuntu/Debian images, saving disk space and minimizing the attack surface.

2. Standardized compose.yaml Over docker-compose.yml

The new Compose file adheres to the preferred filename compose.yaml, which is the official standard defined by the Docker Compose Specification.

services:
  server:
    build:
      context: .
    ports:
      - 3000:3000
    environment:
      - NODE_ENV=production

Notice that the top-level version: '3.8' attribute is gone. If you are still adding that line, it’s completely redundant—Compose v2 deprecated and ignores this field.

3. The .dockerignore File: Keeping Build Contexts Lean

Accidentally sending a 400MB node_modules folder from your local machine to the Docker daemon is the primary culprit behind sluggish build times. Worse yet, inadvertently leaking a .env file containing production secrets into an image is a severe security hazard. docker init handles this upfront with a curated ignore list tailored to your framework.

Advanced: Database Integration Without Race Conditions

During the setup wizard, the tool asks whether your app requires a database. Selecting PostgreSQL or MySQL prompts Docker to automatically inject a database service into compose.yaml, complete with persistent volume storage and secure secret management.

Here is what a complete PostgreSQL stack configuration looks like:

services:
  server:
    build:
      context: .
    ports:
      - 8000:8000
    depends_on:
      db:
        condition: service_healthy
    environment:
      - POSTGRES_HOST=db
      - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
    secrets:
      - db-password

  db:
    image: postgres:16-alpine
    restart: unless-stopped
    user: postgres
    secrets:
      - db-password
    environment:
      - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
      - POSTGRES_USER=postgres
      - POSTGRES_DB=app_db
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  db-data:

secrets:
  db-password:
    file: db/password.txt

The real elegance here is the use of condition: service_healthy paired with a PostgreSQL healthcheck (via pg_isready). The web service waits until the database is fully ready to accept connections before starting up. This eliminates the need for cumbersome wait-for-it.sh scripts to prevent startup race condition crashes.

Pro Tips for Using docker init in Production

Integrating this command into your team’s daily workflow will be much smoother if you keep these four tips in mind:

  • Always commit your code before running: If your directory already contains a Dockerfile or compose.yaml, the tool will prompt for overwrite confirmation. Run a quick git commit or create a new branch beforehand so you can easily diff or roll back changes if needed.
  • Use it as a baseline template for unsupported stacks: Working with Elixir, PHP, or Ruby stacks not yet listed in the wizard? Choose Other or borrow a Node/Python template to grab a solid multi-stage structure and clean volume conventions.
  • Keep BuildKit enabled: The # syntax=docker/dockerfile:1 directive and --mount=type=cache flag require BuildKit. Keep this default enabled in the Docker CLI (enabled by default in v23.0+).
  • Secure secret files: The db/password.txt file is generated to mount passwords securely. Be sure to add this path to your .gitignore right away to avoid accidentally committing database credentials to GitHub.

Stop wasting time piecing together random Docker configurations from the internet. Run docker init in your terminal to set up your project with clean, secure, and optimized container configurations from day one.

Share: