Can't connect my app with postgres inside a docker container - python

app_dockerfile
FROM python:latest
WORKDIR /app
COPY requirements.txt /app
RUN pip3 install -r /app/requirements.txt
ADD sqlalch.py /app/sqlalch.py
CMD [ "python3", "sqlalch.py" ]
my_compose.yml
version: '3.3'
services:
postgres_db:
image: postgres:14.2
container_name: postgres_db
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=mydb
- POSTGRES_HOST_AUTH_METHOD=trust
expose:
- "5432"
#ports:
# - "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- mynet
app:
build:
context: .
dockerfile: app_dockerfile
depends_on:
- postgres_db
restart: always
links:
- postgres_db:postgres_db
networks:
- mynet
volumes:
postgres_data:
networks:
mynet:
driver: bridge
Python script sqlalch.py
from sqlalchemy import (create_engine, Column, Integer,
String, Date, desc, ForeignKey)
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
DATABASE_URI = 'postgresql+psycopg2://postgres:postgres#postgres_db:5432/mydb'
engine = create_engine(DATABASE_URI)
Session = sessionmaker(engine)
session = Session()
Base = declarative_base()
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String(30))
author = Column(String(30))
pages = Column(Integer)
published = Column(Date)
def __repr__(self):
return f'{self.title}, {self.author}, {self.pages},{self.published}\n'
class Library(Base):
__tablename__ = 'library'
id = Column(Integer, primary_key=True)
city = Column(String(50))
street = Column(String(80))
state = Column(String(50))
book_id = Column(Integer, ForeignKey('books.id'))
book_rel = relationship('Book')
def __repr__(self):
return f'{self.id}, {self.city} - {self.book_rel}\n'
Base.metadata.create_all(engine)
def instert_books():
title = str(input('Book title name: '))
author = str(input('Book author name: '))
pages = int(input('Book pages: '))
published = str(input('Book published data (M/D/YYY): '))
book = Book(title=title, author=author, pages=pages, published=published)
session.add(book)
session.commit()
def instert_library():
city = str(input('City: '))
street = str(input('Street: '))
state = str(input('State: '))
book_id = str(input('Book id: '))
libr = Library(city=city, street=street, state=state, book_id=book_id)
session.add(libr)
session.commit()
def view_the_table():
books = session.query(Book).order_by(desc(Book.published)).all()
print(books)
def view_library():
library = session.query(Library).order_by(Library.book_id).all()
print(library)
# instert_books()
# instert_library()
# view_the_table()
view_the_table()
view_library()
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2cfe63663c36 app_app "python3 sqlalch.py" 16 minutes ago Restarting (1) 36 seconds ago app_app_1
5f4936a55286 postgres:14.2 "docker-entrypoint.s…" 16 minutes ago Up 16 minutes 5432/tcp postgres_db
$ docker run -ti app_app /bin/bash
root#f52dc749e0ed:/app# ls
requirements.txt sqlalch.py
root#f52dc749e0ed:/app# python3 sqlalch.py
RESULT
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/impl.py", line 143, in _do_get
return self._create_connection()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 256, in _create_connection
return _ConnectionRecord(self)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 371, in __init__
self.__connect()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 665, in __connect
with util.safe_reraise():
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
compat.raise_(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 590, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 597, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "postgres_db" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "podtgres_db" (::1) and accepting
TCP/IP connections on port 5432?
(Background on this error at: https://sqlalche.me/e/14/e3q8)
I do not make sense :(
I tried everything and it's not working but quickly works when I set the ports: 5432:5432 and set localhost:5432 in python script with my host machine but not with docker host.
What can I do wrong, does anyone have any idea;

Related

Setting up a Postgres DB for Django with Fly.io

I'm a novice trying to spin up my first webapp with a combination of Fly.io, Django, and a postgres DB but I'm having some trouble and can't find an answer in walkthroughs or Q&A.
I've set up a simple "Hello world" Django app (models.py is empty so far) and I'm trying to get all the components up and running before I build it out any further.
I've successfully deployed my app on Fly.io with no errors
I've created a postgres cluster on Fly.io using the instructions here: https://fly.io/docs/postgres/
I've attached the cluster to my app, which generates a DB and sets an environment variable with the appropriate details (username, password, port, host, dbname)
I've updated my settings.py file:
DATABASES = {}
DATABASES["default"] = dj_database_url.config(conn_max_age=600, ssl_require=True)
I've added to my fly.toml:
[[services]]
internal_port = 5432 # Postgres instance
protocol = "tcp"
# Open port 10000 for plaintext connections.
[[services.ports]]
handlers = []
port = 10000
I've confirmed I can get into the psql shell with flyctl postgres connect -a MYAPP-pg
But unfortunately when I run python manage.py migrate to check that everything is working, I get the following error:
File "<my_path>\venv\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection
self.connect()
File "<my_path>\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "<my_path>\venv\lib\site-packages\django\db\backends\base\base.py", line 263, in connect
self.connection = self.get_new_connection(conn_params)
File "<my_path>\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "<my_path>\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection
connection = Database.connect(**conn_params)
File "<my_path>\venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not translate host name "top2.nearest.of.MYAPP-pg.internal" to address: Unknown host
Any ideas what might be happening? Any help would be very much appreciated!

MongoDB shows timeout error when connected with flask over docker

I've been trying to connect flask with mongodb over docker but constantly get the timeout error. Here's my code and error below. Please let me know where I've gone wrong? Thanks.
Also, I've intentionally chosen port 27018 instead of 27017
app.py code:
from pymongo import MongoClient
client = MongoClient(host="test_mongodb",
port = 27018,
username = "root",
password = "rootpassword",
authSource = "admin"
)
#db is same as directory created to identify database
#default port is 27017
db = client.aNewDB
#db is a new database
UserNum = db["UserNum"]
#UserNum is a new Collection
UserNum.insert_one({'num_of_users':0})
docker-compose.yml
version: '3'
services:
web:
build: ./Web
ports:
- "5000:5000"
links:
- db #Web is dependent on db
db:
image: mongo:latest
hostname: test_mongodb
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
ports:
- 27018:27018
Error during docker-compose up:
web_1 | Traceback (most recent call last):
web_1 | File "app.py", line 21, in <module>
web_1 | UserNum.insert_one({'num_of_users':0})
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/collection.py", line 628, in insert_one
web_1 | comment=comment,
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/collection.py", line 562, in _insert_one
web_1 | self.__database.client._retryable_write(acknowledged, _insert_command, session)
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1447, in _retryable_write
web_1 | with self._tmp_session(session) as s:
web_1 | File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__
web_1 | return next(self.gen)
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1729, in _tmp_session
web_1 | s = self._ensure_session(session)
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1712, in _ensure_session
web_1 | return self.__start_session(True, causal_consistency=False)
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1657, in __start_session
web_1 | self._topology._check_implicit_session_support()
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/topology.py", line 538, in _check_implicit_session_support
web_1 | self._check_session_support()
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/topology.py", line 555, in _check_session_support
web_1 | readable_server_selector, self.get_server_selection_timeout(), None
web_1 | File "/usr/local/lib/python3.7/site-packages/pymongo/topology.py", line 240, in _select_servers_loop
web_1 | % (self._error_message(selector), timeout, self.description)
web_1 | pymongo.errors.ServerSelectionTimeoutError: test_mongodb:27018: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 62fa0685c58c2b61f79ea52e, topology_type: Unknown, servers: [<ServerDescription ('test_mongodb', 27018) server_type: Unknown, rtt: None, error=NetworkTimeout('test_mongodb:27018: timed out')>]>
flask_project_web_1 exited with code 1
In docker-compose config file, ports means expose specified ports from container network to host network, it does not do anything to tell the mongodb container to serve at port 27018, therefore, the mongodb will still open the port at 27017 even you specified the port option, therefore, you should tell the mongodb container by using the command option.
Add this line command: mongod --port 27018 into the db service, then it should be working.
like:
db:
image: mongo:latest
hostname: test_mongodb
command: mongod --port 27018
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
ports:
- 27018:27018

Python/Docker - Unknown server host 'db' when migrating

I am trying to migrate a program using python manage.py db migrate in my Visual Studio terminal but when I run it I am getting an error named (2005, "Unknown server host 'db' (11001)"). I am also using the SQLAlchemy library as well to use it alongside flask to create my app. I have found some solutions on StackOverflow and GitHub like trying to recreate my network https://github.com/docker-library/mysql/issues/644 and trying to import MySQLdb and using MySQLdb.connect() "Unknown MySQL server host" when using Flask in Python, but when I try both of these solutions on my program using Visual Studio they don't work.
Here is the error that I am getting in it's full form:
Traceback (most recent call last):
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\base.py", line 2336, in _wrap_pool_connect
return fn()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 304, in unique_connection
return _ConnectionFairy._checkout(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 778, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 495, in checkout
rec = pool._do_get()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\impl.py", line 241, in _do_get
return self._create_connection()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 309, in _create_connection
return _ConnectionRecord(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 440, in __init__
self.__connect(first_connect_check=True)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
compat.raise_(
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise_
raise exception
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 656, in __connect
connection = pool._invoke_creator(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\strategies.py", line 114, in connect
return dialect.connect(*cargs, **cparams)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\default.py", line 493, in connect
return self.dbapi.connect(*cargs, **cparams)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 123, in Connect
return Connection(*args, **kwargs)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2005, "Unknown server host 'db' (11001)")
Here are my required files respectivly:
Dockerfile:
FROM python:3.9
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app
CMD python main.py
requirements.txt:
Flask==1.1.2
Flask-SQLAlchemy==2.4.4
SQLAlchemy==1.3.20
Flask-Migrate==2.6.0
Flask-Script==2.0.6
Flask-Cors==3.0.9
requests==2.25.0
werkzeug==1.0.1
mysqlclient==2.1.0
pika==1.1.0
itsdangerous==2.0.1
wolframalpha==5.0.0
docker-compose.yml:
version: '3.8'
services:
backend:
build:
context: .
dockerfile: Dockerfile
command: 'python main.py'
ports:
- 8001:5000
volumes:
- .:/app
depends_on:
- db
queue:
build:
context: .
dockerfile: Dockerfile
command: 'python -u consumer.py'
depends_on:
- db
db:
image: mysql:5.7.22
restart: always
environment:
MYSQL_DATABASE: veganetworkscript
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
volumes:
- .dbdata:/var/lib/mysql
ports:
- 33068:3306
And finally my manage.py file:
from main import app, db
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
main.py:
from flask_cors import CORS
from sqlalchemy import UniqueConstraint
from vegaaimain.vegamain import main
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from dataclasses import dataclass
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#db/veganetworkscript'
CORS(app)
db = SQLAlchemy(app)
class Product(db.Model):
id: int
title: str
image: str
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
title = db.Column(db.String(200))
image = db.Column(db.String(200))
class VegaScriptRun(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
title = db.Column(db.String(200))
description = db.Column(db.String(400))
image = db.Column(db.String(200))
main()
class ProductUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
product_id = db.Column(db.Integer)
UniqueConstraint('product_id', 'user_id', name='user_product_unique')
#app.route('/api/products')
def index():
return jsonify(Product.query.all())
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
What exactly am I missing or potentially doing wrong here, thank you!
Make changes as follow and it should work:
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#127.0.0.1:33068/veganetworkscript'
But this will only work for migration when your docker container is not running. You can reach the host machine within the container on ip address 172.17.0.1. So your database URI should be
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#172.17.0.1:33068/veganetworkscript'
Also checkout this link
https://www.digitalocean.com/community/tutorials/how-to-use-flask-sqlalchemy-to-interact-with-databases-in-a-flask-application

docker-compose with multiple postgres databases from sql dumps

I know this may seem like a duplicate of docker-compose with multiple databases, but I still can't manage to get it working after going through the answers.
Here is my docker-compose.yml:
version: '3'
services:
backend:
image: backend:1.0
build: ./backend
ports:
- "9090:9090"
depends_on:
- db
- ppt
environment:
- DATABASE_HOST=db
db:
image: main_db:26.03.18
restart: always
build: ./db
ports:
- "5432:5432"
ppt:
image: ppt_generator:1.0
build: ./ppt
ports:
- "6060:6060"
login:
image: login:1.0
build: ./login
ports:
- "7070:7070"
depends_on:
- login_db
login_db:
image: login_db:27.04.2018
restart: always
build: ./login_db
ports:
- "5433:5433"
Notice that I have one db on port 5433 and the other on 5432. However, when I run docker ps after starting the containers I get the following. I don't fully understand what is going on with the ports.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
997f816ddff3 backend:1.0 "/bin/sh -c 'pytho..." About a minute ago Up About a minute 0.0.0.0:9090->9090/tcp backendservices_backend_1
759546109a66 login:1.0 "/bin/sh -c 'pytho..." About a minute ago Up About a minute 0.0.0.0:7070->7070/tcp, 9090/tcp backendservices_login_1
a2a26b72dd0c login_db:27.04.2018 "docker-entrypoint..." About a minute ago Up About a minute 5432/tcp, 0.0.0.0:5433->5433/tcp backendservices_login_db_1
3f97de7fc41e main_db:26.03.18 "docker-entrypoint..." About a minute ago Up About a minute 0.0.0.0:5432->5432/tcp backendservices_db_1
1a61e741ccba ppt_generator:1.0 "/bin/sh -c 'pytho..." About a minute ago Up About a minute 0.0.0.0:6060->6060/tcp backendservices_ppt_1
Both my db dockerfiles are essentially identical except for the port number I expose:
FROM postgres:9.6.3
ENV POSTGRES_USER ludo
ENV POSTGRES_PASSWORD password
ENV POSTGRES_DB login
EXPOSE 5433
ADD db_dump.sql /docker-entrypoint-initdb.d
This is the error I get:
backend_1 | Traceback (most recent call last):
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 2147, in _wrap_pool_connect
backend_1 | return fn()
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 387, in connect
backend_1 | return _ConnectionFairy._checkout(self)
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 766, in _checkout
backend_1 | fairy = _ConnectionRecord.checkout(pool)
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 516, in checkout
backend_1 | rec = pool._do_get()
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 1138, in _do_get
backend_1 | self._dec_overflow()
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
backend_1 | compat.reraise(exc_type, exc_value, exc_tb)
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
backend_1 | raise value
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 1135, in _do_get
backend_1 | return self._create_connection()
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 333, in _create_connection
backend_1 | return _ConnectionRecord(self)
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 461, in __init__
backend_1 | self.__connect(first_connect_check=True)
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/pool.py", line 651, in __connect
backend_1 | connection = pool._invoke_creator(self)
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 105, in connect
backend_1 | return dialect.connect(*cargs, **cparams)
backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 393, in connect
backend_1 | return self.dbapi.connect(*cargs, **cparams)
backend_1 | File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect
backend_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
backend_1 | psycopg2.OperationalError: could not connect to server: Connection refused
backend_1 | Is the server running on host "localhost" (127.0.0.1) and accepting
backend_1 | TCP/IP connections on port 5432?
backend_1 | could not connect to server: Cannot assign requested address
backend_1 | Is the server running on host "localhost" (::1) and accepting
backend_1 | TCP/IP connections on port 5432?
backend_1 |
Why is the db not running on port 5432? It used to work when I only had one database and now with two it seems to be confused...?
UPDATE
I can access the databases respectively on ports 5432 and 5433 locally. However, from my backend container I can't. My backend container seems to not be receiving anything running on port 5432. How do I make db container port 5432 visible to the backend container?
UPDATE
After a lot of fiddling around I got it to work. As #Iarwa1n suggested, you map one db as such "5432:5432" and the other as such "5433:5432". The error I encountered was due to how I was calling postgres from the application itself. It is important to realize the postgres host is not localhost anymore, but whatever name you gave your database service in docker-compose.yaml. In my case; db for backend and login_db for the login service. Additionally, I had to change my driver from postgresql to postgres – not sure why this is...
As such, my db_url ended up looking like this from within my python backend app:
postgres://ludo:password#db:5432/main_db
And defined in this way:
DATABASE_CONFIG = {
'driver': 'postgres',
'host': 'db',
'user': 'ludo',
'password': 'password',
'port': 5432,
'dbname': main_db
}
db_url = '{driver}://{user}:{password}#{host}:{port}/{dbname}'.format(database_config)
Two things to note:
1) Regardless of how you mapped your ports, you always have to connect to postgres default port 5432 from within your app
2) If you're using the requests python library (as was I) then make sure to change the url appropriately as well. For example I had a ppt service I was calling via the requests library and I had to change the url to:
'http://ppt:6060/api/getPpt' instead of 'http://localhost:6060/api/getPpt'
The postgres process on both your machines listens to 5432, as this is the default behavior. Just by EXPOSE you do not change that, this just means, that the container exposes port 5433 instead of 5432. But on this port no process is listening.
Try to change the following:
FROM postgres:9.6.3
ENV POSTGRES_USER ludo
ENV POSTGRES_PASSWORD password
ENV POSTGRES_DB login
EXPOSE 5432
ADD db_dump.sql /docker-entrypoint-initdb.d
and then change the docker-compose like this:
login_db:
image: login_db:27.04.2018
restart: always
build: ./login_db
ports:
- "5433:5432"
Now you can access the "db" at 5432 (from the host) and "login_db" at 5433 from the host. Note, that you still need to use 5432 to access one of the dbs from another container.

OperationalError: (OperationalError) (2003, "Can't connect to MySQL server on '192.168.129.139' (111)") None None

I am trying to create a remote database using mysql on an Ubuntu machine running 12.04.
It has a root user with remote login enabled and no password.I have started the server.
output of
sudo netstat -tap | grep mysql
shows
tcp 0 0 localhost:mysql *:* LISTEN 13246/mysqld
I have created a database called nwtopology using (as mentioned root doesn't have a password yet.)
create database nwtopology
grant all privileges on *.* to root#192.168.129.221
FLUSH PRIVILEGES;
From the client machine that also runs Ubuntu 12.04 I use a python script to connect to the remote mysql database using sqlalchemy.
from pox.core import core
import pox.openflow.libopenflow_01 as of
import re
import datetime
import time
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import exists
log = core.getLogger()
engine = create_engine('mysql://root#192.168.129.139/nwtopology', echo=False)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
class SourcetoPort(Base):
""""""
__tablename__ = 'source_to_port'
id = Column(Integer, primary_key=True)
port_no = Column(Integer)
src_address = Column(String,index=True)
#-----------------------------------------
def __init__(self, src_address,port_no):
""""""
self.src_address = src_address
self.port_no = port_no
The create_engine() call is failing with the following error.
POX 0.1.0 (betta) / Copyright 2011-2013 James McCauley, et al.
Traceback (most recent call last):
File "/home/karthik/ms_thesis/pox/pox/boot.py", line 89, in do_import2
__import__(name, globals(), locals())
File "/home/karthik/ms_thesis/pox/custom/tutorial.py", line 39, in <module>
Base.metadata.create_all(engine)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/schema.py", line 2515, in create_all
tables=tables)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2230, in _run_visitor
conn = self.contextual_connect(close_with_result=False)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2340, in contextual_connect
self.pool.connect(),
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 210, in connect
return _ConnectionFairy(self).checkout()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 371, in __init__
rec = self._connection_record = pool._do_get()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 697, in _do_get
con = self._create_connection()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 174, in _create_connection
return _ConnectionRecord(self)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 256, in __init__
self.connection = self.__connect()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 316, in __connect
connection = self.__pool._creator()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/strategies.py", line 80, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 280, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (OperationalError) (2003, "Can't connect to MySQL server on '192.168.129.139' (111)") None None
I cannot figure out why this is happening?Any help is greatly appreciated?
Looks like the mysql server is configured to listen only on localhost.
You can test this by running telnet 192.168.129.139 3306 from your client machine.
Most probable reason - mysqld (=MySQL daemon) is configured to do so.
Please try to follow Configuration step described here:
Edit the /etc/mysql/my.cnf file to configure MySQL to listen for connections from network hosts, change the bind-address directive to the server's IP address. For example, in your case, replace 192.168.0.5 with 192.168.129.139.
From:
bind-address = 192.168.0.5
to:
bind-address = 192.168.129.139
If there is no such entry and you cannot connect, create a new line.
You may also try commenting out the line instead.
After making a change to /etc/mysql/my.cnf the MySQL daemon will need to be restarted:
sudo systemctl restart mysql.service
Then test with telnet or by running your application once again. Also netstat would have second entry for mysqld.

Categories