Dockerfile can be used in a variety of scenarios and needs. Below are several different Dockerfile examples and their respective application scenarios.
1. Python web applications
Application scenarios:
Build and deploy a Python web application using the Flask framework.
Dockerfile example:
# 使用 Python 3.8 基础镜像
FROM python:3.8
# 设置工作目录
WORKDIR /app
# 安装依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 拷贝源码到工作目录
COPY . .
# 设置环境变量
ENV FLASK_APP=app.py
# 暴露端口
EXPOSE 5000
# 运行 Flask 应用
CMD ["flask", "run", "--host=0.0.0.0"]
2. Node.js applications
Application scenarios:
Build and deploy a backend service using Node.js and Express.
Dockerfile example:
# 使用 Node 14 基础镜像
FROM node:14
# 创建应用目录
WORKDIR /usr/src/app
# 安装依赖
COPY package*.json ./
RUN npm install
# 拷贝源代码
COPY . .
# 暴露端口
EXPOSE 8080
# 启动应用
CMD ["npm", "start"]
3. Java applications built in multiple stages
Application scenarios:
Used to build Java applications and use multi-stage builds to reduce the size of the final image.
Dockerfile example:
# 使用 Maven 基础镜像进行构建
FROM maven:3.6.3-jdk-11 AS build
WORKDIR /build
COPY . .
RUN mvn clean package
# 运行阶段
FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=build /build/target/my-app.jar .
EXPOSE 8080
CMD ["java", "-jar", "my-app.jar"]
4. Database mirroring
Application scenarios:
Create a preconfigured MySQL database image suitable for development and testing.
Dockerfile example:
# 使用 MySQL 基础镜像
FROM mysql:5.7
# 添加数据库初始化脚本
ADD setup.sql /docker-entrypoint-initdb.d
# 设置环境变量(例如,数据库名和密码)
ENV MYSQL_DATABASE=mydatabase
ENV MYSQL_ROOT_PASSWORD=mypassword