在容器环境中使用Nginx搭建文件服务器是一个高效且轻量级的解决方案。以下是详细步骤:
首先,在宿主机上创建用于存储文件的目录结构:
mkdir -p ~/file-server/{uploads,downloads}
chmod -R 777 ~/file-server # 确保Nginx有权限访问
创建nginx.conf
文件:
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
# 文件上传配置
location /upload {
client_max_body_size 100M; # 设置最大上传文件大小
upload_pass @upload_endpoint;
upload_store /usr/share/nginx/uploads;
upload_store_access user:rw group:rw all:rw;
upload_set_form_field $upload_field_name.name "$upload_file_name";
upload_set_form_field $upload_field_name.content_type "$upload_content_type";
upload_set_form_field $upload_field_name.path "$upload_tmp_path";
upload_aggregate_form_field "$upload_field_name.md5" "$upload_file_md5";
upload_aggregate_form_field "$upload_field_name.size" "$upload_file_size";
upload_pass_form_field "^submit$|^description$";
upload_cleanup 400 404 499 500-505;
}
location @upload_endpoint {
return 200 "Upload successful: $upload_file_name";
}
# 文件下载配置
location /downloads {
alias /usr/share/nginx/downloads;
autoindex on; # 启用目录列表
autoindex_exact_size off; # 显示文件大小(KB/MB)
autoindex_localtime on; # 使用本地时间
}
# 首页
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
}
FROM nginx:alpine
# 创建必要的目录
RUN mkdir -p /usr/share/nginx/uploads \
&& mkdir -p /usr/share/nginx/downloads \
&& chown -R nginx:nginx /usr/share/nginx
# 复制配置文件
COPY nginx.conf /etc/nginx/nginx.conf
# 暴露端口
EXPOSE 80
# 构建镜像
docker build -t nginx-file-server .
# 运行容器
docker run -d \
--name file-server \
-p 8080:80 \
-v ~/file-server/uploads:/usr/share/nginx/uploads \
-v ~/file-server/downloads:/usr/share/nginx/downloads \
nginx-file-server
使用curl上传文件:
curl -F "file=@/path/to/your/file.txt" http://localhost:8080/upload
~/file-server/downloads
目录http://localhost:8080/downloads
修改nginx.conf,在server块中添加:
location /downloads {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
然后在Dockerfile中添加:
RUN apk add --no-cache openssl \
&& printf "username:$(openssl passwd -crypt password)\n" > /etc/nginx/.htpasswd
创建docker-compose.yml
文件:
version: '3'
services:
file-server:
image: nginx-file-server
build: .
ports:
- "8080:80"
volumes:
- ./file-server/uploads:/usr/share/nginx/uploads
- ./file-server/downloads:/usr/share/nginx/downloads
restart: unless-stopped
然后运行:
docker-compose up -d
client_max_body_size
和超时设置通过以上步骤,您可以在容器中快速搭建一个功能完整的Nginx文件服务器,支持文件上传和下载功能。