-1

I've followed a lot of answers here in stackoverflow, created a firewall rule and tried everything and I just can't create database in MySQL container. I'm able successfully to log into the MySQL server but keep keep getting this:

mysql> SHOW TABLES FROM access_log;
ERROR 1049 (42000): Unknown database 'access_log'

In my python file when I run it I keep getting this error:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on `'%-.100s:%u' (%s) (Warning: %u format: a real number is required, not str)`

even though my port is 3306 and my host is like the container's name - 'db'. app.py:

from flask import Flask, request, make_response
import mysql.connector
import datetime

app = Flask(__name__)

server_config={
    'user': 'root',
    'password': 'password',
    'host': 'db',
    'database': 'access_log',
    'port': 3306,
}
conn = mysql.connector.connect(**server_config)

# conn = mysql.connector.connect(
#     user='root',
#     password='password',
#     host='db',  # Use the hostname of the MySQL container as defined in the Docker Compose file
#     database='access_log',
#     port=3306,  # Use the port number of the MySQL container
# )

print(f"Connecting to MySQL database {conn.database} on host {conn.host}:{conn.port}...")

# Create a table for access logs if it doesn't exist
cursor=conn.cursor()
print('db has been connected')

create_table_query = '''
    CREATE TABLE IF NOT EXISTS `access_log` (
        id INT AUTO_INCREMENT PRIMARY KEY,
        client_ip VARCHAR(255),
        internal_ip VARCHAR(255),
        access_time DATETIME
    )
'''
try:
    cursor.execute(create_table_query)
    conn.commit()
    print("Table created successfully.")
except mysql.connector.Error as err:
    print(f"Error creating table: {err}")

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()
    sql = "INSERT INTO access_log (client_ip, internal_ip, access_time) VALUES (%s, %s, %s)"
    val = (client_ip, internal_ip, current_time)
    
    try:
        cursor = conn.cursor(dictionary=True) # Use dictionary cursor
        cursor.execute(sql, val)
        conn.commit()
        app.logger.debug(f"Inserted values into access_log table: {val}")
    except Exception as e:
        conn.rollback()
        app.logger.exception(f"Error inserting values into access_log table: {val}, error: {e}")


    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:

version: '3'
services:                                        
  nginx:                                          
    image: nginx:latest
    ports:
      - 80:80
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro     
    depends_on:                                    
      - app
    restart: always

  app:
    build:
      context: ./app
    ports:
      - "5000"
    deploy:
      replicas: 3
    volumes:
      - ./app_logs:/app/logs
    depends_on:                                    
      - db
    restart: always                   
  
  db: 
    image: mysql
    container_name: db
    hostname: db
    ports:
      - '3306:3306'
    environment:
      MYSQL_DATABASE: 'access_log'
      MYSQL_USER: 'root'
      MYSQL_ROOT_PASSWORD: 'password'
    volumes:
      - ./db/data:/var/lib/mysql
      - ./db/logs:/var/log/mysql
    restart: always
    
volumes:
  app_logs:
  db_data:
  db_logs:
Inbar Manor
  • 101
  • 1
  • 10
  • `MYSQL_DATABASE` should have created that database. Perhaps it wasn't specified the first time the container was created? – erik258 Apr 22 '23 at 16:21
  • @erik258 I'm new on docker so this is possible. How can I fix this now? – Inbar Manor Apr 22 '23 at 16:30
  • If there's nothing important in the database server you can destroy the stuff in `./db/data`. Otherwise you can connect to `db` and create the database manually – erik258 Apr 22 '23 at 16:37
  • The database is only created if the mysql data dir is empty. If the data dir is already populated, none of the the environment vars are used. Although this was asked for a password, you are in the exact same situation as [this other question](https://stackoverflow.com/questions/59838692/mysql-root-password-is-set-but-getting-access-denied-for-user-rootlocalhost/59839180#59839180) – Zeitounator Apr 22 '23 at 17:20
  • @erik258 after `CREATE DATABASE access_log;` I got `Can't create database 'access_log'; database exists` and saw that suddenly `access_log` appears but in `SHOW TABLES;` I got `Empty set` meaning I still have this cennection error – Inbar Manor Apr 23 '23 at 07:05
  • @Zeitounator I see now `access_log` without running `docker-compose down -v` but my table is empty and on app.py debugger I still get this error `Can't connect to MySQL server on `'%-.100s:%u' (%s) ` so `docker-compose down -v` will fix it? – Inbar Manor Apr 23 '23 at 07:08
  • 1
    You are using a bind mont. `docker-compose down -v` will not remove it as explained in the linked answer. Just delete the content of the folder and start over as already proposed by erik258 above. – Zeitounator Apr 23 '23 at 07:28
  • 2
    Ho and just noticed that: `MYSQL_USER: root` is an error and can lead to unexpected problems. Remove it or replace with an other user name you want to use in your db. See https://stackoverflow.com/questions/60021273/why-isnt-my-docker-entrypoint-initdb-d-script-as-specified-in-docker-compose-y/60021761#60021761 – Zeitounator Apr 23 '23 at 07:32
  • @Zeitounator I removed `MYSQL_USER: root` from my docker-compose file and it worked. thank you so much! – Inbar Manor Apr 23 '23 at 13:50

1 Answers1

0

I followed the comments and I removed MYSQL_USER: root from my docker-compose file. I also changed host to my computer's IP address and it fixed my problem.

Inbar Manor
  • 101
  • 1
  • 10