I am trying to connect to MySQL database using Docker Compose and I get the following error
Traceback (most recent call last):
| File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 268, in _open_connection
| self._cmysql.connect(**cnx_kwargs)
| _mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '172.22.0.2:3306' (110)
|
| The above exception was the direct cause of the following exception:
| Traceback (most recent call last):
| File "//script.py", line 19, in <module>
| cnx = mysql.connector.connect(host='172.22.0.2', user='user', password='pass', database='db', port=3306)
| File "/usr/local/lib/python3.9/site-packages/mysql/connector/pooling.py", line 286, in connect
| return CMySQLConnection(*args, **kwargs)
| File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 101, in __init__
| self.connect(**kwargs)
| File "/usr/local/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 1108, in connect
| self._open_connection()
| File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 273, in _open_connection..
| raise get_mysql_exception(mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '172.22.0.2:3306'
In my programm I have to containers: for python script and for MySQL database. Both containers are built successfully and db container starts just fine.
172.22.0.2 stands for ip address in network I've created (see docker-compose).
My python script simply connects to the database using mysql-connector.
The code is the following
Dockerfile for script
FROM python:3.9
COPY script.py script.py
RUN pip install mysql-connector-python
script.py
import mysql.connector
cnx = mysql.connector.connect(host='172.22.0.2', user='user', password='pass', database='db', port=3306)
docker-compose.yaml
version: "3"
services:
db:
image: mysql
container_name: db
command: '--init-file /data/app/init.sql'
ports:
- "3306:3306"
volumes:
- "./init.sql:/data/app/init.sql"
environment:
MYSQL_DATABASE: "db"
MYSQL_USER: "user"
MYSQL_PASSWORD: "pass"
MYSQL_ROOT_PASSWORD: "pass"
networks:
net:
ipv4_address: 172.22.0.2
script:
build:
context: ./
dockerfile: Dockerfile
depends_on:
- db
links:
- db
container_name: script
command: sh -c "sleep 10s ; python script.py"
networks:
net:
ipv4_address: 172.22.0.3
networks:
net:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.22.0.0/24
gateway: 172.22.0.1
init.sql
CREATE DATABASE IF NOT EXIST db;
USE db;
Related
My configuration is as follows:
I am running a Django-REST backend, with a MySQL database. I am trying to run the Django backend in its own Docker container, as well as running a MySQL database in its own Django container. It seems that Django is not able to connect to the MySQL database when my containers are running.
Database settings in Django:
DATABASES = {
"default": {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
"NAME": os.environ.get("SQL_DATABASE", BASE_DIR / "db.sqlite3"),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", "5432"),
}
}
Dockerfile:
FROM python:3.10.2-slim-buster
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
RUN apt update \
&& apt install -y --no-install-recommends python3-dev \
default-libmysqlclient-dev build-essential default-mysql-client \
&& apt autoclean
RUN pip install --no-cache-dir --upgrade pip
COPY ./requirements.txt /code/
RUN pip install --no-cache-dir -r requirements.txt
COPY ./neura-dbms-backend /code/
EXPOSE 7000
Requirements.txt:
Django
djangorestframework
django-cors-headers
requests
boto3
django-storages
pytest
mysqlclient==2.1.1
django-use-email-as-username
djangorestframework-simplejwt
gunicorn
docker-compose.yml:
version: "3.8"
services:
neura-dbms-backend:
build:
context: ./DBMS/neura-dbms-backend
command: [sh, -c, "python manage.py runserver 0.0.0.0:7000"]
image: neura-dbms-backend
container_name: neura-dbms-backend
volumes:
- ./DBMS/neura-dbms-backend/neura-dbms-backend:/code
ports:
- 7000:7000
networks:
- docker-network
environment:
- DEBUG=1
- SECRET_KEY=${SECRET_KEY_DBMS}
- DJANGO_ALLOWED_HOSTS=${DJANGO_ALLOWED_HOSTS}
- DJANGO_ALLOWED_ORIGINS=${DJANGO_ALLOWED_ORIGINS}
- JWT_KEY=${JWT_KEY}
- SQL_ENGINE=django.db.backends.mysql
- SQL_DATABASE=db_neura_dbms
- SQL_USER=neura_dbms_user
- SQL_PASSWORD=super_secure_password
- SQL_HOST=db_neura_dbms
- SQL_PORT=5432
depends_on:
- "db_neura_dbms"
db_neura_dbms:
image: mysql:latest
volumes:
- mysql_data_db_neura_dbms:/var/lib/mysql/
environment:
- MYSQL_DATABASE=db_neura_dbms
- MYSQL_USER=neura_dbms_user
- MYSQL_PASSWORD=super_secure_password
- MYSQL_ROOT_PASSWORD=super_secure_password
networks:
- docker-network
networks:
docker-network:
driver: bridge
volumes:
mysql_data_db_neura_dbms:
I am able to build images for Django and the Database, but when I try to run the containers, I get the following error from the Django container:
neura-dbms-backend | System check identified no issues (0 silenced).
neura-dbms-backend | Exception in thread django-main-thread:
neura-dbms-backend | Traceback (most recent call last):
neura-dbms-backend | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
neura-dbms-backend | self.connect()
neura-dbms-backend | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
neura-dbms-backend | return func(*args, **kwargs)
neura-dbms-backend | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 263, in connect
neura-dbms-backend | self.connection = self.get_new_connection(conn_params)
neura-dbms-backend | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
neura-dbms-backend | return func(*args, **kwargs)
neura-dbms-backend | File "/usr/local/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection
neura-dbms-backend | connection = Database.connect(**conn_params)
neura-dbms-backend | File "/usr/local/lib/python3.10/site-packages/MySQLdb/__init__.py", line 123, in Connect
neura-dbms-backend | return Connection(*args, **kwargs)
neura-dbms-backend | File "/usr/local/lib/python3.10/site-packages/MySQLdb/connections.py", line 185, in __init__
neura-dbms-backend | super().__init__(*args, **kwargs2)
neura-dbms-backend | MySQLdb.OperationalError: (2002, "Can't connect to MySQL server on 'db_neura_dbms' (115)")
What am I missing? Thanks!
So I added a script so that Django waits for the mysql database to be ready before it connects:
#!/bin/bash
if [ "$SQL_HOST" = "db" ]
then
echo "Waiting for mysql..."
while !</dev/tcp/$SQL_HOST/$SQL_PORT; do sleep 1; done;
echo "MySQL started"
fi
# python manage.py migrate
exec "$#"
When I first run the Docker containers, it seems that MySQL runs through some sort of setup, Django then tries to connect and fails.
If I then kill the containers, and run them again, the MySQL setup is finished, and Django is able to connect to the database. I wonder if there is a way for Django to wait for this setup to be finished as well?
depends_on only waits till the database container is started, but in this case, after the container is started it still takes some time for mysql to make the system ready for connection.
what you can do is create a command file (This is for postgres, you can make one for yours, you will need to add raised mysql exception instead of Psycopg2Error )
import time
from psycopg2 import OperationalError as Psycopg2Error
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Django command to wait for database
"""
def handle(self, *args, **options):
"""
Command entrypoint
"""
self.stdout.write("Checking database availability\n")
db_up = False
seconds_cnt = 0
while not db_up:
try:
self.check(databases=['default'])
db_up = True
self.stdout.write(
self.style.WARNING(
"Available within {} seconds".format(seconds_cnt)))
self.stdout.write(self.style.SUCCESS("Database available!"))
except(Psycopg2Error, OperationalError):
seconds_cnt += 1
self.stdout.write(
self.style.WARNING(
"Database unavailable waiting... {} seconds"
.format(seconds_cnt)))
time.sleep(1)
Your command can be updated with,
command: >
sh -c "python manage.py wait_for_db &&
python manage.py runserver 0.0.0.0:87000"
I am in the process of Dockerizing my project, and the following is my docker-compose.yml:
version: '3.8'
services:
server:
image: server
environment:
DB_HOST: 0.0.0.0
DB_DATABASE: dev
DB_PORT: 3306
DB_USER: dev
DB_PASSWORD: dev
ports:
- "4000:4000"
restart: on-failure
depends_on:
database:
condition: service_started
database:
image: mysql:latest
command: --default-authentication-plugin=mysql_native_password
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: dev
MYSQL_PASSWORD: dev
MYSQL_DATABASE: dev
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
and the Dockerfile for server:
FROM elixir:latest
EXPOSE 4000
RUN mkdir /server
COPY . /server
WORKDIR /server
RUN mix local.rebar --force
RUN mix local.hex --force
RUN mix deps.get
RUN mix do compile
CMD [ "sh", "/server/entry.sh" ]
where entry.sh is:
# Exit on failure
set -e
mix ecto.create
mix ecto.migrate
mix run priv/repo/seeds.exs
exec mix phx.server
When I run this using docker compose up, I get an error that Phoenix can't connect to the MySQL database. I have tried using hosts 0.0.0.0 and localhost, however both don't work.
This is the corresponding section of my config/dev.exs:
config :app, App.Repo
username: System.get_env("DB_USER"),
password: System.get_env("DB_PASSWORD"),
hostname: System.get_env("DB_HOST"),
database: System.get_env("DB_DATABASE"),
port: 3306,
stacktrace: true,
pool_size: 10
The following is the exact error message I get:
server-1 | 11:23:07.417 [error] GenServer #PID<0.272.0> terminating
server-1 | ** (DBConnection.ConnectionError) (0.0.0.0:3306) connection refused - :econnrefused
server-1 | (db_connection 2.4.3) lib/db_connection/connection.ex:100: DBConnection.Connection.connect/2
server-1 | (connection 1.1.0) lib/connection.ex:622: Connection.enter_connect/5
server-1 | (stdlib 4.2) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
server-1 | Last message: nil
server-1 | State: MyXQL.Connection
server-1 |
server-1 | 11:23:07.430 [error] GenServer #PID<0.278.0> terminating
server-1 | ** (DBConnection.ConnectionError) (0.0.0.0:3306) connection refused - :econnrefused
server-1 | (db_connection 2.4.3) lib/db_connection/connection.ex:100: DBConnection.Connection.connect/2
server-1 | (connection 1.1.0) lib/connection.ex:622: Connection.enter_connect/5
server-1 | (stdlib 4.2) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
server-1 | Last message: nil
server-1 | State: MyXQL.Connection
server-1 | ** (Mix) The database for App.Repo couldn't be created: %RuntimeError{message: "killed"}
server-1 exited with code 1
I installed airflow in local, using MySQL, celery executor, and rabbitmq
now I install airflow in the docker to set up Airflow HA Scheduler with YAML file:
version: '3'
x-airflow-common:
&airflow-common
image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.3.4}
environment:
&airflow-common-env
AIRFLOW__CORE__EXECUTOR: CeleryExecutor
# AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow#postgres/airflow
# AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow#postgres/airflow
# AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow#postgres/airflow
# AIRFLOW__CELERY__BROKER_URL: redis://:#redis:6379/0
# AIRFLOW__CORE__FERNET_KEY: ''
# AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true'
# AIRFLOW__CORE__LOAD_EXAMPLES: 'true'
# AIRFLOW__API__AUTH_BACKENDS: 'airflow.api.auth.backend.basic_auth'
# _PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-}
AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: mysql://airflow:password#localhost/airflow
AIRFLOW__CORE__SQL_ALCHEMY_CONN: mysql://airflow:password#localhost/airflow
AIRFLOW__CELERY__RESULT_BACKEND: db+mysql://airflow:password#localhost:3306/airflow
AIRFLOW__CELERY__BROKER_URL: pyamqp://airflow:password#localhost:5672/myvhost
AIRFLOW__CORE__FERNET_KEY: 'LgPLCqY0vrVDAI7s7eR408ZfRNm_CekdALmA1CJtYgs='
AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true'
AIRFLOW__CORE__LOAD_EXAMPLES: 'false'
AIRFLOW__API__AUTH_BACKENDS: 'airflow.api.auth.backend.basic_auth'
_PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-}
volumes:
- ./dags:/opt/airflow/dags
- ./logs:/opt/airflow/logs
- ./plugins:/opt/airflow/plugins
user: "${AIRFLOW_UID:-50000}:0"
depends_on:
&airflow-common-depends-on
rabbitmq:
condition: service_healthy
mysql:
condition: service_healthy
services:
# postgres:
# image: postgres:13
# environment:
# POSTGRES_USER: airflow
# POSTGRES_PASSWORD: airflow
# POSTGRES_DB: airflow
# volumes:
# - postgres-db-volume:/var/lib/postgresql/data
# healthcheck:
# test: ["CMD", "pg_isready", "-U", "airflow"]
# interval: 5s
# retries: 5
# restart: always
mysql:
image: mysql:5.7
environment:
MYSQL_DATABASE: airflowdb
MYSQL_USER: airflow
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
volumes:
- mysql-db-volume:/var/lib/mysql/airflowdb
healthcheck:
test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]
interval: 5s
retries: 5
ports:
- '3306:3306'
restart: always
# redis:
# image: redis:latest
# expose:
# - 6379
# healthcheck:
# test: ["CMD", "redis-cli", "ping"]
# interval: 5s
# timeout: 30s
# retries: 50
# restart: always
rabbitmq:
image: rabbitmq:3.9
container_name: rabbitmq
ports:
- 5672:5672
- 15672:15672
volumes:
- ~/.docker-conf/rabbitmq/data/:/var/lib/rabbitmq/
- ~/.docker-conf/rabbitmq/log/:/var/log/rabbitmq
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:15672"]
interval: 30s
timeout: 10s
retries: 5
networks:
- rabbitmq_go_net
volumes:
# postgres-db-volume:
mysql-db-volume:
To deploy Airflow on Docker Compose, I fetch file from airflow docker-compose then edit environment to the same airflow.config (sql_alchemy, reesult_backend, broker) and mysql, rabbitmq instead of postgres, redis.
when I run docker-compose up airflow-init get error
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/docker/api/client.py", line 268, in _raise_for_status
response.raise_for_status()
File "/home/linhnq/.local/lib/python3.10/site-packages/requests/models.py", line 1022, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 502 Server Error: Bad Gateway for url: http+docker://localhost/version
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/docker/api/client.py", line 214, in _retrieve_server_version
return self.version(api_version=False)["ApiVersion"]
File "/usr/lib/python3/dist-packages/docker/api/daemon.py", line 181, in version
return self._result(self._get(url), json=True)
File "/usr/lib/python3/dist-packages/docker/api/client.py", line 274, in _result
self._raise_for_status(response)
File "/usr/lib/python3/dist-packages/docker/api/client.py", line 270, in _raise_for_status
raise create_api_error_from_http_exception(e)
File "/usr/lib/python3/dist-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 502 Server Error for http+docker://localhost/version: Bad Gateway ("b'Bad response from Docker engine'")
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/docker-compose", line 33, in <module>
sys.exit(load_entry_point('docker-compose==1.29.2', 'console_scripts', 'docker-compose')())
File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 81, in main
command_func()
File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 200, in perform_command
project = project_from_options('.', options)
File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 60, in project_from_options
return get_project(
File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 152, in get_project
client = get_client(
File "/usr/lib/python3/dist-packages/compose/cli/docker_client.py", line 41, in get_client
client = docker_client(
File "/usr/lib/python3/dist-packages/compose/cli/docker_client.py", line 170, in docker_client
client = APIClient(use_ssh_client=not use_paramiko_ssh, **kwargs)
File "/usr/lib/python3/dist-packages/docker/api/client.py", line 197, in __init__
self._version = self._retrieve_server_version()
File "/usr/lib/python3/dist-packages/docker/api/client.py", line 221, in _retrieve_server_version
raise DockerException(
docker.errors.DockerException: Error while fetching server API version: 502 Server Error for http+docker://localhost/version: Bad Gateway ("b'Bad response from Docker engine'")
how can I fix this error?
thanks,`
I am trying to test my Quart application (pager) that connects to a MySQL instance in a docker container called master-db, but after a few retries I get a hypercorn error:
pager | Traceback (most recent call last):
pager | File "/usr/local/bin/hypercorn", line 8, in <module>
pager | sys.exit(main())
pager | File "/usr/local/lib/python3.9/site-packages/hypercorn/__main__.py", line 267, in main
pager | run(config)
pager | File "/usr/local/lib/python3.9/site-packages/hypercorn/run.py", line 34, in run
pager | worker_func(config)
pager | File "/usr/local/lib/python3.9/site-packages/hypercorn/asyncio/run.py", line 187, in asyncio_worker
pager | _run(
pager | File "/usr/local/lib/python3.9/site-packages/hypercorn/asyncio/run.py", line 229, in _run
pager | loop.run_until_complete(main(shutdown_trigger=shutdown_trigger))
pager | File "/usr/local/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
pager | return future.result()
pager | File "/usr/local/lib/python3.9/site-packages/hypercorn/asyncio/run.py", line 69, in worker_serve
pager | sockets = config.create_sockets()
pager | File "/usr/local/lib/python3.9/site-packages/hypercorn/config.py", line 177, in create_sockets
pager | insecure_sockets = self._create_sockets(self.bind)
pager | File "/usr/local/lib/python3.9/site-packages/hypercorn/config.py", line 240, in _create_sockets
pager | sock.bind(binding)
pager | socket.gaierror: [Errno -2] Name does not resolve
pager exited with code 1
The code works locally and has been fully tested, but I don't know where I have gone wrong :(
The docker-compose file is:
version: "3.8"
networks:
localdev:
driver: bridge
services:
master-db:
image: mysql:8.0
container_name: master-db
command: --default-authentication-plugin=mysql_native_password
restart: always
ports:
- "4000:3306"
environment:
MYSQL_ROOT_PASSWORD: password_for_stackoverflow
volumes:
- ./database/docker:/etc/mysql/conf.d
networks:
- localdev
pager:
build:
context: .
dockerfile: Dockerfile.pager
container_name: pager
ports:
- "2020:2020"
networks:
- localdev
depends_on:
- master-db
Docker.pager:
FROM python:3-alpine
RUN pip install --upgrade pip
RUN pip install hypercorn
RUN pip install mysql-connector
RUN pip install quart
COPY src/common /app/common
COPY src/pager /app/pager
WORKDIR /app
CMD ["hypercorn", "pager:app", "--bind", "'0.0.0.0:2020'"]
The problem is not that you can’t connect to the MySQL instance, the problem is that Hypercorn is trying to listen on a socket and failing.
CMD ["hypercorn", "pager:app", "--bind", "'0.0.0.0:2020'"]
Have you tried removing the single quotes from the bind parameter?
CMD ["hypercorn", "pager:app", "--bind", "0.0.0.0:2020"]
I am trying to setup some containers for my NestJS + TypeORM + MySQL environment by using Docker Compose in a Windows 10 host, but I am getting an ECONNREFUSED error:
connect ECONNREFUSED 127.0.0.1:3306 +2ms
backend_1 | Error: connect ECONNREFUSED 127.0.0.1:3306
backend_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)
backend_1 | --------------------
backend_1 | at Protocol._enqueue (/usr/src/app/node_modules/mysql/lib/protocol/Protocol.js:144:48)
backend_1 | at Protocol.handshake (/usr/src/app/node_modules/mysql/lib/protocol/Protocol.js:51:23)
backend_1 | at PoolConnection.connect (/usr/src/app/node_modules/mysql/lib/Connection.js:116:18)
backend_1 | at Pool.getConnection (/usr/src/app/node_modules/mysql/lib/Pool.js:48:16)
backend_1 | at /usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:793:18
backend_1 | at new Promise (<anonymous>)
backend_1 | at MysqlDriver.createPool (/usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:790:16)
backend_1 | at MysqlDriver.<anonymous> (/usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:278:51)
backend_1 | at step (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:141:27)
backend_1 | at Object.next (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:122:57)
I have created the following Dockerfile to configure the NestJS API container:
FROM node:12-alpine
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
EXPOSE 3000
#CMD ["npm", "start"]
CMD /wait-for-it.sh db:3306 -- npm start
COPY . .
And then I reference this from Docker Compose with the following docker-compose.yml:
version: "3.8"
networks:
app-tier:
driver: bridge
services:
db:
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
expose:
- "3306"
ports:
- "3306:3306"
networks:
- app-tier
environment:
MYSQL_DATABASE: school
MYSQL_ALLOW_EMPTY_PASSWORD: ok
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: dbuser
MYSQL_PASSWORD: dbuser
MYSQL_ROOT_HOST: '%'
backend:
depends_on:
- db
build: .
ports:
- "3000:3000"
networks:
- app-tier
Finally, I set the TypeORM configuration to match with the Docker Compose file:
export const DB_CONFIG: TypeOrmModuleOptions = {
type: 'mysql',
host: 'db',
port: 3306,
username: 'dbuser',
password: 'dbuser',
database: 'school',
entities: [], // We specify the entities in the App Module.
synchronize: true,
};
I am kind of new to Docker Compose, but I have tried many things like changing the output port to 3307, setting an explicit network... and the port 3306 is free in my host OS when I run it. Any help?
Edit 1
I have included MYSQL_ROOT_HOST and wait-for-it.sh as suggested, but still no results.
I think your db is taking more time to start and your app is starting before the db, try something like this for your docker-compose.yml file:
version: "3.8"
networks:
app-tier:
driver: bridge
services:
db:
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
expose:
- "3306"
ports:
- "3306:3306"
networks:
- app-tier
environment:
MYSQL_DATABASE: school
MYSQL_ALLOW_EMPTY_PASSWORD: ok
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: dbuser
MYSQL_PASSWORD: dbuser
MYSQL_ROOT_HOST: '%'
backend:
depends_on:
- db
build: .
command: bash -c 'while !</dev/tcp/db/3306; do sleep 1; done; npm start'
ports:
- "3000:3000"
networks:
- app-tier