" mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'db:3306' (-2 Na



我正在运行docker组成的flask和MySQL容器,但我面临这个错误"MySQL.connector.errors. interfaceerror: 2003: Can't connect to MySQL server on 'db:3306' (-2 Name or service not known)">

docker version: 20.10.7

请帮我解决这个问题

我的项目结构是:

flaskProject6/
├── app/
│   ├── app.py
│   |── Dockerfile
│   │── requirements.txt
│──db/
│   |── init.sql
├── docker-compose.yml

Flask==2.0.1
mysql_connector

app.py

from typing import List, Dict
from flask import Flask
import mysql.connector
import json
app = Flask(__name__)

def favorite_colors() -> List[Dict]:
config = {
'user': 'root',
'password': 'root',
'host':'db',
'port': '3306',
'database': 'knights'
}
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
cursor.execute('SELECT * FROM favorite_colors')
results = [{name: color} for (name, color) in cursor]
cursor.close()
connection.close()
return results

@app.route('/')
def index() -> str:
return json.dumps({'favorite_colors': favorite_colors()})

if __name__ == '__main__':
app.run(host='0.0.0.0')

Dockerfile

# Use an official Python runtime as an image
FROM python:3.9.4
# The EXPOSE instruction indicates the ports on which a container
# will listen for connections
# Since Flask apps listen to port 5000  by default, we expose it
EXPOSE 5000
# Sets the working directory for following COPY and CMD instructions
# Notice we haven’t created a directory by this name - this instruction
# creates a directory with this name if it doesn’t exist
WORKDIR /app
# Install any needed packages specified in requirements.txt
COPY requirements.txt /app
RUN pip3 install -r requirements.txt
# Run app.py when the container launches
COPY app.py /app
CMD python app.py

init.sql

CREATE DATABASE IF NOT EXISTS knights;
use knights;
CREATE TABLE favorite_colors (
name VARCHAR(20),
color VARCHAR(10)
);
INSERT INTO favorite_colors
(name, color)
VALUES
('Lancelot', 'blue'),
('Galahad', 'yellow');

docker-compose.yml

services:
app:
build: ./app
depends_on:
- db
ports:
- "5000:5000"
db:
image: mysql:8.0.26
ports:
- "32000:3306"
environment:
MYSQL_ROOT_USER: root
MYSQL_ROOT_PASSWORD: root
MYSQL_PASSWORD: root
MYSQL_DATABASE: knights
volumes:
- ./db:/docker-entrypoint-initdb.d/:ro
restart: always

输出:创建步骤:

C:UsersKarthikDesktopflaskProject6>docker-compose up --build
Creating network "flaskproject6_default" with the default driver
Building app
[+] Building 15.6s (10/10) FINISHED
=> [internal] load build definition from Dockerfile                                                                                                          0.1s
=> => transferring dockerfile: 32B                                                                                                                           0.0s
=> [internal] load .dockerignore                                                                                                                             0.1s
=> => transferring context: 2B                                                                                                                               0.0s
=> [internal] load metadata for docker.io/library/python:3.9.4                                                                                              15.0s
=> [internal] load build context                                                                                                                             0.2s
=> => transferring context: 63B                                                                                                                              0.0s
=> [1/5] FROM docker.io/library/python:3.9.4@sha256:03ac9e7e04a401af550774bc974c03d02fd0e74c8a185f7ab902e1be99d1ec98                                         0.0s
=> CACHED [2/5] WORKDIR /app                                                                                                                                 0.0s
=> CACHED [3/5] COPY requirements.txt /app                                                                                                                   0.0s
=> CACHED [4/5] RUN pip3 install -r requirements.txt                                                                                                         0.0s
=> CACHED [5/5] COPY app.py /app                                                                                                                             0.0s
=> exporting to image                                                                                                                                        0.2s
=> => exporting layers                                                                                                                                       0.0s
=> => writing image sha256:3bf215f9a31f612a8d9c75ac845731ccda8654fc189f7ae2fce7baf7d4086403                                                                  0.0s
=> => naming to docker.io/library/flaskproject6_app                                                                                                          0.0s
Creating flaskproject6_db_1 ... done
Creating flaskproject6_app_1 ... done
Attaching to flaskproject6_db_1, flaskproject6_app_1
db_1   | 2021-08-16 09:13:42+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.26-1debian10 started.
db_1   | 2021-08-16 09:13:43+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1   | 2021-08-16 09:13:43+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.26-1debian10 started.
db_1   | 2021-08-16 09:13:43+00:00 [Warn] [Entrypoint]: MYSQL_PASSWORD specified, but missing MYSQL_USER; MYSQL_PASSWORD will be ignored
db_1   | 2021-08-16 09:13:43+00:00 [Note] [Entrypoint]: Initializing database files
db_1   | 2021-08-16T09:13:43.466536Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.26) initializing of server in progress as process 44
db_1   | 2021-08-16T09:13:43.520113Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
app_1  |  * Serving Flask app 'app' (lazy loading)
app_1  |  * Environment: production
app_1  |    WARNING: This is a development server. Do not use it in a production deployment.
app_1  |    Use a production WSGI server instead.
app_1  |  * Debug mode: off
app_1  |  * Running on all addresses.
app_1  |    WARNING: This is a development server. Do not use it in a production deployment.
app_1  |  * Running on http://172.22.0.3:5000/ (Press CTRL+C to quit)
db_1   | 2021-08-16T09:13:45.953897Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
db_1   | 2021-08-16T09:13:49.561880Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
db_1   | 2021-08-16T09:13:49.562474Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
db_1   | 2021-08-16T09:13:49.794492Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initia
lize-insecure option.
db_1   | 2021-08-16 09:13:57+00:00 [Note] [Entrypoint]: Database files initialized
db_1   | 2021-08-16 09:13:57+00:00 [Note] [Entrypoint]: Starting temporary server
db_1   | 2021-08-16T09:13:57.883021Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.26) starting as process 93
db_1   | 2021-08-16T09:13:57.913341Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
db_1   | 2021-08-16T09:13:58.259382Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
db_1   | 2021-08-16T09:13:59.028875Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
db_1   | 2021-08-16T09:13:59.029924Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
db_1   | 2021-08-16T09:13:59.046457Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
db_1   | 2021-08-16T09:13:59.047374Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this
channel.
db_1   | 2021-08-16T09:13:59.061686Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible t
o all OS users. Consider choosing a different directory.
db_1   | 2021-08-16T09:13:59.321041Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
db_1   | 2021-08-16T09:13:59.322457Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.26'  socket: '/var/run/mysqld/mysqld.so
ck'  port: 0  MySQL Community Server - GPL.
db_1   | 2021-08-16 09:13:59+00:00 [Note] [Entrypoint]: Temporary server started.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
db_1   | 2021-08-16 09:14:09+00:00 [Note] [Entrypoint]: Creating database knights
db_1   |
db_1   | 2021-08-16 09:14:09+00:00 [Note] [Entrypoint]: /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sql
db_1   |
db_1   |
db_1   | 2021-08-16 09:14:09+00:00 [Note] [Entrypoint]: Stopping temporary server
db_1   | 2021-08-16T09:14:09.597391Z 12 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.26).
db_1   | 2021-08-16T09:14:11.561783Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.26)  MySQL Community Server - GPL.
db_1   | 2021-08-16 09:14:11+00:00 [Note] [Entrypoint]: Temporary server stopped
db_1   |
db_1   | 2021-08-16 09:14:11+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.
db_1   |
db_1   | 2021-08-16T09:14:12.524304Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.26) starting as process 1
db_1   | 2021-08-16T09:14:12.537075Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
db_1   | 2021-08-16T09:14:12.946871Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
db_1   | 2021-08-16T09:14:13.229828Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
db_1   | 2021-08-16T09:14:13.230032Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
db_1   | 2021-08-16T09:14:13.231501Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
db_1   | 2021-08-16T09:14:13.231876Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this
channel.
db_1   | 2021-08-16T09:14:13.239435Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible t
o all OS users. Consider choosing a different directory.
db_1   | 2021-08-16T09:14:13.261895Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx
.sock
db_1   | 2021-08-16T09:14:13.262051Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.26'  socket: '/var/run/mysqld/mysqld.so
ck'  port: 3306  MySQL Community Server - GPL.

我也试过使用run

PS C:UsersKarthik> docker run -p 8085:5000 flaskproject6_app
* Serving Flask app 'app' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://172.17.0.2:5000/ (Press CTRL+C to quit)
[2021-08-16 07:30:40,748] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/mysql/connector/network.py", line 482, in open_connection
addrinfos = socket.getaddrinfo(self.server_host,
File "/usr/local/lib/python3.9/socket.py", line 953, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/app/app.py", line 30, in index
return json.dumps({'favorite_colors': favorite_colors()})
File "/app/app.py", line 18, in favorite_colors
connection = mysql.connector.connect(**config)
File "/usr/local/lib/python3.9/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/usr/local/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 716, in connect
self._open_connection()
File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection.py", line 206, in _open_connection
self._socket.open_connection()
File "/usr/local/lib/python3.9/site-packages/mysql/connector/network.py", line 500, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'db:3306' (-2 Name or service not known)
172.17.0.1 - - [16/Aug/2021 07:30:40] "GET / HTTP/1.1" 500 -

我通过将映像的版本从8.0.26更改为mysql:5.6得到了解决方案

最新更新