我有这个简单的烧瓶应用程序:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import time
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://{user}:{pwd}@{host}:{port}/{db}'.format(
user = 'postgres',
pwd = '123456',
host = 'db',
port = '5432',
db = 'test'
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
if __name__ == "__main__":
db.create_all()
app.run(host='0.0.0.0', port=80)
然后使用以下Dockerfile
构建它:
FROM python:3.6
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
EXPOSE 80
CMD ["python", "app.py"]
如下:
sudo docker build -t app .
还有我的docker-compose.yml
:
version: "3"
services:
web:
image: app:latest
deploy:
replicas: 1
restart_policy:
condition: on-failure
ports:
- "4000:80"
depends_on:
- db
networks:
- webnet
db:
image: postgres
expose:
- 5432
volumes:
- /var/www/docker-tutorial/data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: 123456
POSTGRES_DB: test
networks:
webnet:
我的requirements.txt
文件:
Flask
Flask-SQLAlchemy
psycopg2
我正在与:
docker stack deploy -c docker-compose.yml getstarted
一切正常,但是连接到数据库时出现以下异常:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "db" to address: Name or service not known
Any Ideas是什么引起异常?另外,我尝试将sqlalchemy的host参数替换为“ getstarted_db”,这是服务的名称,但是也没有用。
答案 0 :(得分:1)
感谢maxm评论,我能够解决问题,问题在于web
和db
服务不在同一个网络中。因此,我的docker-compose.yml
如下所示:
version: "3"
services:
web:
image: hello:latest
deploy:
replicas: 1
restart_policy:
condition: on-failure
ports:
- "4000:80"
depends_on:
- db
networks:
- webnet
db:
image: postgres
expose:
- 5432
volumes:
- /var/www/docker-tutorial/data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: 123456
POSTGRES_DB: test
networks:
- webnet
networks:
webnet: