在我的django项目中,经过各种参考和指南后,我编写了docker-compose.yml
,Dockerfile
文件和build_dev.sh
脚本。
构建完成后,我可以通过转到URL http://0.0.0.0/
来访问hello world页面。现在我要在运行中的Docker容器中创建数据库
docker exec -it django_docker_db_1 bash
使用此命令可以访问db容器
然后我运行命令su - postgres
现在,当我尝试运行createuser --createdb --password myproject
时,它会要求输入密码。我输入了与定义脚本相同的密码(在指南中,该密码写为“在询问时,输入与
build_dev.sh脚本。”),但抛出一个错误,提示createuser: error: could not connect to database postgres: FATAL: role "postgres" does not exist
。
请帮助我!
build_dev.sh
#!/usr/bin/env bash
DJANGO_SETTINGS_MODULE="myproject.settings.dev" \
DJANGO_SECRET_KEY="3!^3%bro*!)=1s_g49eqb5&q^4*-m^7p_)q7xkond_b6*lc&&6" \
DATABASE_NAME="myproject" \
DATABASE_USER="myproject" \
DATABASE_PASSWORD="testpassword" \
EMAIL_HOST="localhost" \
EMAIL_PORT="25" \
EMAIL_HOST_USER="" \
EMAIL_HOST_PASSWORD="" \
PIP_REQUIREMENTS="dev.txt" \
docker-compose up --detach --build
docker-compose.yml
version: "3.7"
services:
nginx:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./config/nginx/conf.d:/etc/nginx/conf.d
- static_volume:/home/myproject/static
- media_volume:/home/myproject/media
depends_on:
- gunicorn
gunicorn:
build:
context: .
args:
PIP_REQUIREMENTS: "${PIP_REQUIREMENTS}"
command: bash -c "/home/myproject/env/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 myproject.wsgi:application"
depends_on:
- db
volumes:
- static_volume:/home/myproject/static
- media_volume:/home/myproject/media
expose:
- "8000"
environment:
DJANGO_SETTINGS_MODULE: "${DJANGO_SETTINGS_MODULE}"
DJANGO_SECRET_KEY: "${DJANGO_SECRET_KEY}"
DATABASE_NAME: "${DATABASE_NAME}"
DATABASE_USER: "${DATABASE_USER}"
DATABASE_PASSWORD: "${DATABASE_PASSWORD}"
EMAIL_HOST: "${EMAIL_HOST}"
EMAIL_PORT: "${EMAIL_PORT}"
EMAIL_HOST_USER: "${EMAIL_HOST_USER}"
EMAIL_HOST_PASSWORD: "${EMAIL_HOST_PASSWORD}"
db:
image: postgres:latest
restart: always
environment:
POSTGRES_DB: "${DATABASE_NAME}"
POSTGRES_USER: "${DATABASE_USER}"
POSTGRES_PASSWORD: "${DATABASE_PASSWORD}"
ports:
- 5432
volumes:
- postgres_data:/var/lib/postgresql/data/
volumes:
postgres_data:
static_volume:
media_volume:
Dockerfile
# pull official base image
FROM python:3.8
# accept arguments
ARG PIP_REQUIREMENTS=production.txt
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install dependencies
RUN pip install --upgrade pip setuptools
# create user for the Django project
RUN useradd -ms /bin/bash myproject
# set current user
USER myproject
# set work directory
WORKDIR /home/myproject
# create and activate virtual environment
RUN python3 -m venv env
# copy and install pip requirements
COPY --chown=myproject ./src/myproject/requirements /home/myproject/requirements/
RUN ./env/bin/pip3 install -r /home/myproject/requirements/${PIP_REQUIREMENTS}
# copy Django project files
COPY --chown=myproject ./src/myproject /home/myproject/