0

My code (symfony 5.4) fails to persist data to the database. Here's my setup:-

docker-compose.yaml

...
#MySQL Service
  db:
    image: mysql:5.7.22
    container_name: db
    restart: unless-stopped
    tty: true
    ports:
      - "3316:3306"
    environment:
      MYSQL_DATABASE: pink
      MYSQL_ROOT_PASSWORD: password
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - dbdata:/var/lib/mysql
      - ./docker/mysql/my.cnf:/etc/mysql/my.cnf
    networks:
      - app-network
...

.env

DATABASE_URL="mysql://root:password@db:3316/pink"

ProductController.php

#[Route('/product/create', name: 'product_create')]
    public function createProduct(ManagerRegistry $doctrine): Response
    {
        $entityManager = $doctrine->getManager();

        $product = new Product();
        $product->setName('Keyboard');
        $product->setPrice(1999);
        $product->setDescription('Ergonomic and stylish!');

        // tell Doctrine you want to (eventually) save the Product (no queries yet)
        $entityManager->persist($product);

        // actually executes the queries (i.e. the INSERT query)
        $entityManager->flush();

        return new Response('Saved new product with id '.$product->getId());

    }

The database (docker) container is up and running fine. Here's a test, with success:-

mysql --host=127.0.0.1 --user=root --password=password pink --port=3316 --ssl-mode=disabled

In my .env file I've replaced the string 127.0.0.1 with my docker container name as above: db .

Any ideas please?

cookie
  • 222
  • 3
  • 8
  • 18

2 Answers2

1

Turns out we need to use the default port number for database connections i.e. 3306 . Full db string like thus:

DATABASE_URL="mysql://root:password@db:3306/pink"

I still don't fully understand the idea of internal/external & visibility of port numbers in docker containers

db:
    ...
    ports:
      - "3316:3306"
cookie
  • 222
  • 3
  • 8
  • 18
0

I have the same issue on working with Docrine WSL2 , I had to add this line in /etc/hosts

127.0.0.1 db

And use this config in .env file:

DATABASE_URL="mysql://root:password@db:3306/my_database_name?serverVersion=8.0.3&charset=utf8mb4"
AdminBee
  • 21,637
  • 21
  • 47
  • 71
Fatima
  • 1