对于在mac上使用Django、Python3和Docker的简单应用程序
FROM python:3
ENV PYTHONUNBUFFERED=1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN python3 -m pip install -r requirements.txt
CMD python3 manage.py runserver
COPY . /code/
version: "3.9"
services:
# DB
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: '****'
MYSQL_USER: '****'
MYSQL_PASSWORD: '****'
MYSQL_DATABASE: 'mydb'
ports:
- "3307:3306"
expose:
# Opens port 3306 on the container
- '3307'
volumes:
- $HOME/proj/sql/mydbdata.sql:/mydbdata.sql
# Web app
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
另外,我想要的是在第一次创建映像时执行SQL, 之后,应该装入数据库
volumes:
- $HOME/proj/sql/mydbdata.sql:/mydbdata.sql
看起来Docker正在启动,但从我的浏览器中,我得到了以下响应
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
我错过了什么。请帮忙
创建映像时,django项目似乎已在运行。由于您使用了
command
选项docker-compose.yml
文件,因此在本例中Dockerfile
中不需要CMD
命令我将
Dockerfile
和docker-compose.yml
改写如下:有几件事需要指出
docker-compose up
时,您可能会看到一个错误,因为您的django项目甚至在初始化db之前就已经在运行了。 这很自然。所以您需要自定义命令或shell程序来强制django项目等待尝试连接db李>在我的情况下,我将使用自定义命令
接下来,
wait_for_db.py
。这个文件是我在myapp/management/commands/wait_for_db.py
中创建的。通过这种方式,您可以推迟db连接,直到db就绪。这对我帮助很大详情见Writing custom django-admin command
因此
.sql
文件应该位于mysql容器的/docker-entrypoint-initdb.d
中。有关更多信息,请参见this postdocker-compose down
时,您的数据库将丢失,因为您没有sql文件以外的卷。这不是你想要的,你可能想考虑下面的相关问题 更多 >
编程相关推荐