1. nginx 컨테이너 설치
nginx가 파일 업로드를 지원하려면 nginx-upload-module 모듈을 사용하여 컨테이너를 다운로드하고 실행해야 합니다.
sudo podman pull docker.io/dimka2014/nginx-upload-with-progress-modules:latest sudo podman -d --name nginx -p 83:80 docker.io/dimka2014/nginx-upload-with-progress-modules
이 컨테이너에는 nginx-upload-module 모듈과 nginx-upload-progress -모듈 모듈.
참고이 컨테이너는 Alpine Linux
이고 bash가 없으며 일부 명령이 다른 Linux 배포판과 다릅니다. Alpine Linux
,没有bash,有些命令与其它发行版本的Linux不一样。
使用下面的命令进入容器:
sudo podman exec -it nginx /bin/sh
作为文件服务器, 需要显示本地时间,默认不是本地时间。通过下面一系列命令设置为本地时间:
apk update apk add tzdata echo "Asia/Shanghai" > /etc/timezone rm -rf /etc/localtime cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime apk del tzdata
创建文件服务器的根目录:
mkdir -p /nginx/share
二、配置nginx
配置文件的路径为/etc/nginx/conf.d/default.conf
server { …… charset utf-8; # 设置字符编码,避免中文乱码 location / { root /nginx/share; # 根目录 autoindex on; # 开启索引功能 autoindex_exact_size off; # 关闭计算文件确切大小(单位bytes),只显示大概大小(单位kb、mb、gb) autoindex_localtime on; # 显示本地时间 } }파일 서버로서 기본적으로 현지 시간이 아닌 현지 시간을 표시해야 합니다. 다음 일련의 명령을 통해 현지 시간을 설정하십시오.
nginx -s reload

server { …… charset utf-8; # 设置字符编码,避免中文乱码 client_max_body_size 32m; upload_limit_rate 1M; # 限制上传速度最大1M # 设置upload.html页面路由 location = /upload.html { root /nginx; # upload.html所在路径 } location /upload { # 限制上传文件最大30MB upload_max_file_size 30m; # 设置后端处理交由@rename处理。由于nginx-upload-module模块在存储时并不是按上传的文件名存储的,所以需要自行改名。 upload_pass @rename; # 指定上传文件存放目录,1表示按1位散列,将上传文件随机存到指定目录下的0、1、2、...、8、9目录中(这些目录要手动建立) upload_store /tmp/nginx 1; # 上传文件的访问权限,user:r表示用户只读,w表示可写 upload_store_access user:r; # 设置传给后端处理的表单数据,包括上传的原始文件名,上传的内容类型,临时存储的路径 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_pass_form_field "^submit$|^description$"; # 设置上传文件的md5值和文件大小 upload_aggregate_form_field "${upload_field_name}_md5" "$upload_file_md5"; upload_aggregate_form_field "${upload_field_name}_size" "$upload_file_size"; # 如果出现下列错误码则删除上传的文件 upload_cleanup 400 404 499 500-505; } location @rename { # 后端处理 proxy_pass http://localhost:81; } }
2. nginx 구성
구성 파일의 경로는 /etc/nginx/conf.d입니다. /default.conf,
mkdir -p /tmp/nginx cd /tmp/nginx mkdir 1 2 3 4 5 6 7 8 9 0 chown nginx:root . -R
이제 파일 서비스가 구성되었습니다. 구성을 적용하려면 다음 명령을 사용해야 합니다.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>上传</title> </head> <body> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <form name="upload" method="POST" enctype="multipart/form-data" action="upload"> <input type="file" name="file"/> <input type="submit" name="submit" value="上传"/> </form> </body> </html>3. 파일 업로드 지원1. 위 구성 파일 서버 구성이 완료되었으나 파일을 업로드할 수 없습니다. 파일을 업로드하려면 다음 구성을 수행해야 합니다.
apk add python3 pip3 install bottle pip3 install shutilwhich위 구성에서 임시 저장소는 1개를 기준으로 합니다. -업로드 디렉터리에 있어야 하는 비트 해시입니다. 0~9의 여러 디렉터리를 수동으로 만듭니다.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from bottle import *
import shutil
@post("/upload")
def postExample():
try:
dt = request.forms.dict
filenames = dt.get('file.name')
tmp_path = dt.get("file.tmp_path")
filepaths = dt.get("file.path")
count = filenames.__len__()
dir = os.path.abspath(filepaths[0])
for i in range(count):
print("rename %s to %s" % (tmp_path[i], os.path.join(dir, filenames[i])))
target = os.path.join(dir, filenames[i])
shutil.move(tmp_path[i], target)
shutil.chown(target, "nginx", "root") # 由于shutil.move不会保持用户归属,所以需要显示修改,否则访问时会报403无访问权限
except Exception as e:
print("Exception:%s" % e)
redirect("50x.html") # 如果是在容器中部署的nginx且映射了不同的端口,需要指定IP,端口
redirect('/') # 如果是在容器中部署的nginx且映射了不同的端口,需要指定IP,端口
run(host='localhost', port=81)
2. upload.html을 추가합니다# 开辟一个空间proxied来存储跟踪上传的信息1MB
upload_progress proxied 1m;
server {
……
location ^~ /progress {
# 报告上传的信息
report_uploads proxied;
}
location /upload {
...
# 上传完成后,仍然保存上传信息5s
track_uploads proxied 5s;
}
}
3. 후속 처리 서비스를 추가합니다 먼저 Python과 필수 라이브러리를 설치해야 합니다. <form id="upload" enctype="multipart/form-data" action="/upload" method="post" onsubmit="openProgressBar(); return true;"> <input name="file" type="file" label="fileupload" /> <input type="submit" value="Upload File" /> </form> <div> <div id="progress" > <div id="progressbar" > </div> </div> <div id="tp">(progress)</div> </div> <script type="text/javascript"> var interval = null; var uuid = ""; function openProgressBar() { for (var i = 0; i < 32; i++) { uuid += Math.floor(Math.random() * 16).toString(16); } document.getElementById("upload").action = "/upload?X-Progress-ID=" + uuid; /* 每隔一秒查询一下上传进度 */ interval = window.setInterval(function () { fetch(uuid); }, 1000); } function fetch(uuid) { var req = new XMLHttpRequest(); req.open("GET", "/progress", 1); req.setRequestHeader("X-Progress-ID", uuid); req.onreadystatechange = function () { if (req.readyState == 4) { if (req.status == 200) { var upload = eval(req.responseText); document.getElementById('tp').innerHTML = upload.state; /* 更新进度条 */ if (upload.state == 'done' || upload.state == 'uploading') { var bar = document.getElementById('progressbar'); var w = 400 * upload.received / upload.size; bar.style.width = w + 'px'; } /* 上传完成,不再查询进度 */ if (upload.state == 'done') { window.clearTimeout(interval); } if (upload.state == 'error') { window.clearTimeout(interval); alert('something wrong'); } } } } req.send(null); } </script>

위 내용은 nginx를 사용하여 컨테이너에 업로드 및 다운로드하기 위한 파일 서버를 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

NGINX는 이벤트 중심 아키텍처 및 비동기 처리 기능을 통해 성능을 향상시키고 모듈 식 설계 및 유연한 구성을 통해 확장 성을 향상 시키며 SSL/TLS 암호화 및 요청 속도 제한을 통해 보안을 향상시킵니다.

NGINX는 동시성이 높은 자원 소비 시나리오에 적합하지만 APACHE는 복잡한 구성 및 기능 확장이 필요한 시나리오에 적합합니다. 1.NGINX는 고성능과의 많은 동시 연결을 처리하는 것으로 알려져 있습니다. 2. Apache는 안정성과 풍부한 모듈 지원으로 유명합니다. 선택할 때는 특정 요구에 따라 결정해야합니다.

nginxissentialderformodernwebapplicationsduetoitsrolessareareverseproxy, loadbalancer 및 Webserver, HighperformanceAndscalability를 제공합니다

Nginx를 통해 웹 사이트 보안을 보장하려면 다음 단계가 필요합니다. 1. 기본 구성을 만들고 SSL 인증서 및 개인 키를 지정하십시오. 2. 구성 최적화, HTTP/2 및 OCSPStapling 활성화; 3. 인증서 경로 및 암호화 제품군 문제와 같은 공통 오류 디버그; 4. Let 'sencrypt 및 세션 멀티플렉싱 사용과 같은 응용 프로그램 성능 최적화 제안.

NGINX는 고성능 HTTP 및 리버스 프록시 서버로 높은 동시 연결을 처리하는 데 능숙합니다. 1) 기본 구성 : 포트를 듣고 정적 파일 서비스를 제공합니다. 2) 고급 구성 : 리버스 프록시 및로드 밸런싱을 구현하십시오. 3) 디버깅 기술 : 오류 로그를 확인하고 구성 파일을 테스트하십시오. 4) 성능 최적화 : GZIP 압축을 활성화하고 캐시 정책을 조정합니다.

Nginx 캐시는 다음 단계를 통해 웹 사이트 성능을 크게 향상시킬 수 있습니다. 1) 캐시 영역을 정의하고 캐시 경로를 설정하십시오. 2) 캐시 유효성 기간 구성; 3) 다른 컨텐츠에 따라 다른 캐시 정책을 설정합니다. 4) 캐시 저장 및로드 밸런싱을 최적화합니다. 5) 캐시 효과를 모니터링하고 디버그합니다. 이러한 방법을 통해 NGINX 캐시는 백엔드 서버 압력을 줄이고 응답 속도 및 사용자 경험을 향상시킬 수 있습니다.

dockercompose를 사용하면 Nginx의 배포 및 관리를 단순화 할 수 있으며 Dockerswarm 또는 Kubernetes를 통한 스케일링은 일반적인 관행입니다. 1) DockerCompose를 사용하여 Nginx 컨테이너를 정의하고 실행하십시오. 2) Dockerswarm 또는 Kubernetes를 통한 클러스터 관리 및 자동 스케일링 구현.

NGINX의 고급 구성은 서버 블록 및 리버스 프록시를 통해 구현 될 수 있습니다. 1. 서버 블록을 사용하면 여러 웹 사이트를 한쪽으로 실행할 수있게되면 각 블록은 독립적으로 구성됩니다. 2. 리버스 프록시는 요청을 백엔드 서버로 전달하여로드 밸런싱 및 캐시 가속도를 실현합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기
