My docker compose does not create mysql user,database even though i have passed them as environmental variable.here is my docker-compose.yml.
version: '3.3'
services:
web:
image: zadiki1/posshop-webapp
ports:
- "3000:3000"
depends_on:
- db
- phpmyadmin
environment:
HOST: db
MYSQL_DATABASE: 'posshop'
USER_NAME: 'zadik'
PASSWORD: 'zadik'
db:
image: mysql:8
command: --default-authentication-plugin=mysql_native_password
restart: always
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: 'root'
MYSQL_USER: 'zadik'
MYSQL_PASSWORD: 'zadik'
MYSQL_DATABASE: 'posshop'
MYSQL_ROOT_HOST: '0.0.0.0'
expose:
- '3306'
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: phpmyadmin-dot
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: 'root'
PMA_HOST: db
depends_on:
- db
ports:
- 8000:80
when i go to the mysql server both the database and the user are not created
I have searched online but cant find a solution
2
Answers
The environment variables are used to configure access to existing resources within the database. If you need to have a database
posshop
and a userzadik
in thedb
(mysql:8
) instance, you will need to create these against the database server before you can access them, e.g. fromweb
.It is slightly inconvenient to do this with Docker Compose but, in my experience, a successful solution is to use e.g. a docker volume to persist the database server configuration, create the database and user while the server’s configured to use this for persistence. Then, reference it subsequently in a configuration (as yours) that depends upon it.
It’s possible but more challenging to have another container added to your Docker Compose that creates these assets and blocks e.g.
web
from starting until this is done.Your docker-compose.yml file is correct (at least for the db service). It will create everything you configured – root password, user, and database.
See below:
Using the exact same yaml as you for the db service:
Start containers:
Exec into mysql container:
Connect with root and list databases (which shows posshop):
Connect with user (zadik/zadik):
Additional note: As stated in the other answer you should also create a volume to persist data (although that wasn’t the question).