我在设置 django、docker、nginx 和 gunicorn 时遇到了问题。即使我设置了静态文件,在运行服务器时也无法显示collectstatic
它们。当我使用 nginx 时,我要么收到错误消息,提示我使用的端口已分配,要么如果我更改端口,则会收到“网关错误”,但我仍然能够使用 gunicorn 正在使用的端口 - 在我的情况下是端口 8000。
我的 docker-compose.yml 文件:
version: '3'
services:
db:
image: postgres:latest
container_name: rapid_goat_postgres_server_1
nginx:
image: nginx:latest
container_name: rapid_goat_nginx_1
ports:
- "8000:8000"
volumes:
- .:/code
- ./nginx:/etc/nginx/conf.d
- /static:/static
depends_on:
- web
web:
build: .
container_name: rapid_goat_django
command: bash -c "chmod -R 755 . && cd rapidgoat_scraper_product && python3 manage.py collectstatic --noinput && python3 manage.py makemigrations && python3 manage.py migrate && gunicorn rapidgoat_scraper.wsgi -b 0.0.0.0:8000 --workers 6"
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
我的 nginx 配置文件:
upstream web {
ip_hash;
server web:8000;
}
server {
location /static/ {
autoindex on;
root /code/static/;
}
location / {
proxy_pass http://web/;
}
listen 8000;
server_name localhost;
}
使用上述两个文件时,运行时出现以下错误docker-compose up --build
:
ERROR: for 693800faea42_693800faea42_693800faea42_my_nginx_docker_container Cannot start service nginx: driver failed programming external connectivity on endpoint my_nginx_docker_container (48eab4028fad0c54d8bbf5669fe746c24f293cfeb11dc57c8566d4010a995a83): Bind for 0.0.0.0:8000 failed: port is already allocated
ERROR: for nginx Cannot start service nginx: driver failed programming external connectivity on endpoint my_nginx_docker_container (48eab4028fad0c54d8bbf5669fe746c24f293cfeb11dc57c8566d4010a995a83): Bind for 0.0.0.0:8000 failed: port is already allocated
ERROR: Encountered errors while bringing up the project.
然后,当我从 docker-compose.yml 文件中删除 nginx 服务时,我可以启动 gunicorn 服务器,但它不提供静态文件。我也在应用程序模板中使用,所以我的 django 项目结构如下所示:
- project
-- __init__.py
-- settings.py
-- urls.py
-- wsgi.py
- appname
-- migrations
-- static
--- appname
... then rest of static files like js, css, images... etc
-- templates
--- appname
... then all of my html files. I am using django templating.
-- admin.py
-- apps.py
-- forms.py
-- models.py
-- tests.py
-- views.py
我也在使用 django 2.0.3
编辑:
下面是当我删除 nginx 时出现的相同文件(与我更改 nginx 的端口时相同),并且 gunicorn 不提供静态服务:
我的 docker-compose.yml 文件:
version: '3'
services:
db:
image: postgres:latest
container_name: rapid_goat_postgres_server_1
web:
build: .
container_name: rapid_goat_django
command: bash -c "chmod -R 755 . && cd rapidgoat_scraper_product && python3 manage.py collectstatic --noinput && python3 manage.py makemigrations && python3 manage.py migrate && gunicorn rapidgoat_scraper.wsgi -b 0.0.0.0:8000 --workers 6"
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
哦,我的 Dockerfile 是:
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
RUN mkdir /static
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/