Multiple Container, each one own database

Hi, I’m new to the docker, and I have a question.

How can I, for example, install mysql and 2 wordpress sites

Each one with its own database. (1 mysql container, with 2 different Databases,usernames,and passwords)

And if one day I want to add another site or program that also uses mysql, how do I avoid installing 3 different instances of mysql?

Thanks

services:

  wordpress1:
    image: wordpress
    restart: always
    ports:
      - 8080:80
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: exampleuser01
      WORDPRESS_DB_PASSWORD: examplepass01
      WORDPRESS_DB_NAME: exampledb01
    volumes:
      - wordpress1:/var/www/html

  wordpress2:
    image: wordpress
    restart: always
    ports:
      - 8081:80
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: exampleuser02
      WORDPRESS_DB_PASSWORD: examplepass02
      WORDPRESS_DB_NAME: exampledb02
    volumes:
      - wordpress2:/var/www/html

  db:
    image: mysql:8.0
    restart: always
    environment:
      MYSQL_DATABASE: exampledb
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_RANDOM_ROOT_PASSWORD: '1'
    volumes:
      - db:/var/lib/mysql

Or its better to have 1 instance of mysql running per each app???

Your compose seems correct.

When the containers are within the same compose file, they will be connected to an implicit Docker network. Even better is to use an explicit declared Docker network to attach the containers to it. That can also be used by other compose file services.

The db container will only create a single user, so you need to manually create more users. Or use the same user with different databases.

Personally I prefer bind mounts to Docker volumes. You can’t accidentally delete them as easy and they are easier to backup IMHO.

Note that a single WordPress instance can run multiple sites.

When using multiple containers, usually a reverse proxy is used to handle multiple domains on the same ip:port. Check nginx-proxy with companion or Traefik (example), both can be auto-configured by env vars or labels on target service, manage TLS/SSL.

Hi, thank you very much, regarding the proxy, I am using the nginx proxy manager.

I didn’t understand this:
Personally I prefer bind mounts to Docker volumes. You can’t accidentally delete them as easy and they are easier to backup IMHO.

Isn’t that the same thing I put???

Many Thanks

This is a volume, files are managed by Docker:

This is a bind mount, regular files on host

volumes:
      - ./db:/var/lib/mysql

Check the doc: volume vs bind mount. It’s a bit unfortunate that compose uses volumes for both.