官网:https://docs.docker.com/engine/reference/commandline/init/
简介
docker init
是一个命令行实用程序,可帮助初始化项目中的 Docker 资源。.dockerignore
它根据项目的要求创建Dockerfile
、Compose 文件
。这简化了为项目配置 Docker 的过程,节省时间并降低复杂性。
最新版本docker init支持Go、Python、Node.js、Rust、ASP.NET、PHP 和 Java
如何使用
1. 创建一个flask应用
mkdir flask
cd flask
touch app.py requirements.txt
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_docker():
return '<h1> hello world </h1'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
# requirements.txt
Flask
2. 生成Dockerfile docker-compose.yaml
docker init将扫描您的项目并要求您确认并选择最适合您的应用程序的模板。选择模板后,docker init系统会要求您提供一些特定于项目的信息,并自动为您的项目生成必要的 Docker 资源。
docker init
选择应用程序平台,对于我们正在使用的示例,python.它将为您的项目建议值,例如Python版本port、entrypoint命令
3. 查看生成的Dockerfile
# 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.11.7
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/go/dockerfile-user-best-practices/
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 'app:app' --bind=0.0.0.0:5000
4. 查看生成的docker-compose.yaml文件
它编写了 docker-compose 配置来运行应用程序。由于我们的应用程序不包含与数据库的任何连接,因此它注释掉了数据库容器可能需要的代码。
如果您想在 Flask 应用程序中使用数据库,请从docker-compose
文件中取消注释 db 服务配置,创建一个包含机密的本地文件,然后运行该应用程序。它还生成了.dockerignore
文件。