docker下部署自己镜像的方法(相册管理系统为例)

想开发一个相册管理系统,采用python的flask框架,

1、先在windows上创建这样的目录结构

/photo_gallery
├── app.py
├── requirements.txt
├── Dockerfile
├── static
│   ├── uploads
│   └── thumbnails
└── templates
    └── index.html

2、app.py代码如下

from flask import Flask, request, render_template, redirect, url_for, send_from_directory
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/mnt/-1/photo_gallery'  # 图片存储路径

# 确保上传目录存在
if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])

@app.route('/')
def index():
    # 列出所有图片
    images = os.listdir(app.config['UPLOAD_FOLDER'])
    return render_template('index.html', images=images)

@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return redirect(url_for('index'))
    file = request.files['file']
    if file.filename == '':
        return redirect(url_for('index'))
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
    return redirect(url_for('index'))

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

index.html代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>相册管理</title>
</head>
<body>
    <h1>相册管理</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>
    <h2>图片列表</h2>
    <ul>
        {% for image in images %}
        <li>
            <img src="{{ url_for('uploaded_file', filename=image) }}" width="200">
            <a href="{{ url_for('uploaded_file', filename=image) }}" download>下载</a>
        </li>
        {% endfor %}
    </ul>
</body>
</html>

Dockerfile内容如下:

# 使用官方Python镜像作为基础镜像
FROM python:3.9-slim

# 设置工作目录
WORKDIR /app

# 复制项目文件到容器中
COPY . .

# 安装依赖
RUN pip install --no-cache-dir -r requirements.txt

# 暴露Flask应用的端口
EXPOSE 5000

# 设置环境变量
ENV FLASK_APP=app.py
ENV FLASK_ENV=production

# 启动应用
CMD ["flask", "run", "--host=0.0.0.0"]

requirements.txt内容如下:
 

Flask==2.3.2
Pillow==10.0.0

然后将整个文件夹复制到linux系统里面的root文件夹里,在linux系统中进入上面的photo_gallery目录,输入如下命令:

docker build -t photo_gallery:latest .
docker run -v /mnt/-1/photo_gallery:/mnt/-1/photo_gallery -p 5000:5000 photo_gallery:latest

这里需要注意的是,保存图片的文件夹在docker容器里是看不见的,因此需要将这个外部的文件夹映射到docker容器中。

最后http://地址:5000就可以访问了。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值