DEV Community

Serena Sensini
Serena Sensini

Posted on • Originally published at theredcode.it on

Scopriamo 'docker init'

Docker ha rivoluzionato il modo in cui chi sviluppa crea, impacchetta e distribuisce le loro applicazioni.

I container Docker forniscono un ambiente di runtime leggero, portabile e coerente che può essere eseguito su qualsiasi infrastruttura.

Poco più di un mese fa, il team di Docker ha presentato docker init, un nuovo comando dell’interfaccia della riga di comando (CLI) introdotto come funzionalità beta che semplifica il processo di aggiunta di Docker a un progetto.

Il nuovo comando docker init automatizza la creazione delle risorse Docker necessarie, come i Dockerfile, i file per Docker Compose e i file .dockerignore, in base alle caratteristiche del progetto. Eseguendo il comando docker init, gli sviluppatori possono rapidamente containerizzare i loro progetti.

docker init è uno strumento prezioso per gli sviluppatori che desiderano sperimentare con Docker, conoscere la containerizzazione o integrare Docker nei loro progetti esistenti.

Nota: per utilizzare _ docker init _, gli sviluppatori devono eseguire l’aggiornamento alla versione 4.19.0 o successiva di Docker Desktop ed eseguire il comando nella cartella del progetto di destinazione. docker init rileverà le definizioni del progetto e genererà automaticamente i file necessari per eseguire il progetto in Docker.

‘docker init’ in azione

Dopo aver aggiornato Docker Desktop, ci posizioniamo all’interno della cartella del progetto che vogliamo dockerizzare e andiamo a eseguire tramite il terminale il comando docker init:

$ docker init

>>>
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

Let's get started!

? What application platform does your project use? [Use arrows to move, type to filter]
 Go - suitable for a Go server application
> Python - suitable for a Python server application
 Node - suitable for a Node server application
 Rust - suitable for a Rust server application
 Other - general purpose starting point for containerizing your application
 Don't see something you need? Let us know!
 Quit

Enter fullscreen mode Exit fullscreen mode

In questo caso, ci chiede se il progetto che vogliamo dockerizzare usa una delle tecnologie elencate: scegliamo Python -ovvio- e andiamo avanti:

? What application platform does your project use? Python
? What version of Python do you want to use? (3.8.10)

Enter fullscreen mode Exit fullscreen mode

Indichiamo la versione di Python utilizzata, e procediamo:

? What application platform does your project use? Python
? What version of Python do you want to use? 3.8.10
? What port do you want your app to listen on? 5000

Enter fullscreen mode Exit fullscreen mode

A questo punto, selezioniamo qual è la porta che l’applicazione utilizza per comunicare con altri servizi: usiamo la porta 5000, che è una di quelle utilizzate più comunemente nei progetti che usano gunicorn per la propria applicazione:

? What application platform does your project use? Python
? What version of Python do you want to use? 3.8.10
? What port do you want your app to listen on? 5000
? What is the command to run your app (e.g., gunicorn 'test:app' --bind=0.0.0.0:5000)?

Enter fullscreen mode Exit fullscreen mode

Il comando riportato è quello di esecuzione di un’applicazione molto basica che specifica la porta di cui eseguire il binding dell’applicazione sulla 5000 tramite il modulo chiamato test:app: questo va chiaramente sostituito con il nome del modulo Python (ad esempio, il file test.py) e la funzione che esegue il codice che espone il servizio. Un esempio veloce è il seguente:

# test.py
>>> def app(env, start_response):
... data = b'Hello my world!'
... status = '200'
... response_headers = [
... ('Content-type', 'text/plain'),
... ('Content-Length', str(len(data)))
... ]
... start_response(status, response_headers)
... return iter([data])

Enter fullscreen mode Exit fullscreen mode

Completato questo step, siamo al punto di arrivo: verranno creati un file . dockerignore , un Dockerfile e un compose.yml , seguendo le indicazioni fornite.

? What application platform does your project use? Python
? What version of Python do you want to use? 3.8.10
? What port do you want your app to listen on? 5000
? What is the command to run your app (e.g., gunicorn 'myapp.example:app' --bind=0.0.0.0:5000)? gunicorn 'test:app' --bind=0.0.0.0:5000

CREATED: .dockerignore
CREATED: Dockerfile
CREATED: compose.yaml

✔ Your Docker files are ready!

Take a moment to review them and tailor them to your application.

WARNING: No requirements.txt file found. Be sure to create one that contains the dependencies for your application, including an entry for the gunicorn package, before running your application.

When you're ready, start your application by running: docker compose up --build

Your application will be available at http://localhost:5000

Enter fullscreen mode Exit fullscreen mode

Apriamo il Dockerfile, e diamogli un’occhiata: il file riporta la versione di Python selezionata tramite l’istruzione ARG, un’immagine di base che sfrutta questo parametro, così come la porta 5000 da esporre (vedi_EXPOSE_) e il comando di avvio dell’applicazione (istruzione CMD):

# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/engine/reference/builder/

ARG PYTHON_VERSION=3.8.10
FROM python:${PYTHON_VERSION}-slim as base

# Prevents Python from writing pyc files.
ENV PYTHONDONTWRITEBYTECODE=1

# Keeps Python from buffering stdout and stderr to avoid situations where
# the application crashes without emitting any logs due to buffering.
ENV PYTHONUNBUFFERED=1

WORKDIR /app

# Create a non-privileged user that the app will run under.
# See https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user
ARG UID=10001
RUN adduser \
 --disabled-password \
 --gecos "" \
 --home "/nonexistent" \
 --shell "/sbin/nologin" \
 --no-create-home \
 --uid "${UID}" \
 appuser

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
# Leverage a bind mount to requirements.txt to avoid having to copy them into
# into 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

# Switch to the non-privileged user to run the application.
USER appuser

# Copy the source code into the container.
COPY . .

# Expose the port that the application listens on.
EXPOSE 5000

# Run the application.
CMD gunicorn 'test:app' --bind=0.0.0.0:5000

Enter fullscreen mode Exit fullscreen mode

Queste istruzioni andranno certamente riviste in base alle esigenze, ma è già un ottimo punto di partenza, considerato che ogni comando è opportunamente commentato, così che sia più semplice metterci mano!

docker init è uno strumento prezioso per le persone che sviluppano che desiderano semplificare il processo di aggiunta del supporto Docker ai propri progetti. Automatizza la creazione delle risorse Docker necessarie e può aiutare a standardizzare la creazione delle risorse Docker in diversi progetti.

Questo consente ai/lle developers di concentrarsi sullo sviluppo delle proprie applicazioni e riducendo il rischio di errori e incoerenze, accelerando l’adozione di Docker e la migrazione verso i container!

Tip: l’immagine è stata generata con il modello di Deep.ai, che permette di creare immagini a partire da un testo 😉

Risorse utili

Top comments (0)