I'm new on docker and I've been trying to create 5 containers for:
- nginx
- db
- 3 instances of python app
I successfully created the nginx and db container and they are running (I've checked with
docker-ps
). For some reason my app's container are not running. When I've loged one of them I got this error message:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno 111] Connection refused)")
app.py - UPDATE - I've switched to mysql.connector
and it still doesn't work:
from flask import Flask, request, make_response
import mysql.connector
import datetime
app = Flask(__name__)
conn = mysql.connector.connect(
host='db', # Use the hostname of the MySQL container as defined in the Docker Compose file
port=3306, # Use the port number of the MySQL container
user='root',
password='password',
db='access_log',
)
# Create a table for access logs if it doesn't exist
cursor=conn.cursor()
create_table_query = '''
CREATE TABLE IF NOT EXISTS access_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
client_ip VARCHAR(255),
internal_ip VARCHAR(255),
access_time DATETIME
)
'''
cursor.execute(create_table_query)
conn.commit()
counter=0
@app.route('/')
def home():
global counter
counter += 1
# Get internal IP address
internal_ip = request.environ['REMOTE_ADDR']
# Create cookie with internal IP address that expires in 5 minutes
resp = make_response(internal_ip)
resp.set_cookie('internal_ip', internal_ip, max_age=300)
# Record access log in MySQL database
client_ip = request.remote_addr
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
sql = "INSERT INTO access_logs (client_ip, internal_ip, access_time) VALUES (%s, %s, %s)"
val = (client_ip, internal_ip, current_time)
cursor = conn.cursor(dictionary=True) # Use dictionary cursor
cursor.execute(sql, val)
conn.commit()
return internal_ip
@app.route('/showcount')
def show_count():
global counter
return f'Global Counter: {counter}'
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
docker-compose - UPDATED -
I've added depends_on: - db
used and it still doesn't work
version: '3'
services:
nginx:
image: nginx:latest
ports:
- 80:80
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- app
networks:
- my_network
app:
build:
context: ./app
ports:
- "5000"
deploy:
replicas: 3
volumes:
- ./app_logs:/app/logs
depends_on:
- db
networks:
- my_network
db:
image: mysql
ports:
- '3306:3306'
environment:
- MYSQL_ROOT_PASSWORD=password
volumes:
- ./db/data:/var/lib/mysql
- ./db/logs:/var/log/mysql
networks:
- my_network
volumes:
app_logs:
db_data:
db_logs:
networks:
my_network:
Dockerfile:
FROM python:3.9
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0", "--port=5000"]
requirements.txt:
Flask
mysql-connector-python