Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

docker-compose & Exposed Ports

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

We just started our MySQL docker container thanks to docker-compose. So... ah... now what? How can we talk to that database? Great question!

Start by running just:

docker-compose

This lists all the commands that you can use with docker-compose. Most of these we won't need to worry about. But one good one is ps, which stands for "process status". Try it:

docker-compose ps

This shows all the containers that docker-compose is running for this project... which is just one right now. Ah, and check this out! Port 3306 of the container is being shared to our local machine on port 32773. This is a random port number that will be different each time we restart the container.

Connecting to the MySQL Docker Container

This means that we can talk to the MySQL server in the container via port 32773! Let me show you. I actually do have mysql installed on my local machine, so I can say mysql -u root --password=password because, in our docker-compose.yaml file, that's what we set the root user password to. Then --host=127.0.0.1 - to talk to my local computer - and --port= set to this one right here: 32773. Try it!

mysql -u root --password=password --host=127.0.0.1 --port=32773

Boom! We are inside of the container talking to MySQL! By the way, if you don't have MySQL installed locally, you can also do this by running:

docker-compose exec database mysql -u root --password=password

That will "execute" the mysql command inside the container that's called database.

Anyways, now that we're here, we can do normal stuff like:

SHOW DATABASES

... or even create a new database called docker_coolness:

CREATE DATABASE docker_coolness

There it is! I'll type exit to get out.

Stopping and Destroying the Containers

When you're done with the containers and want to turn them off, you can do that with:

docker-compose stop

Or the more common:

docker-compose down

This loops through all of the services in docker-compose.yaml and, not only stops each container, but also removes its image. It's like completely deleting that "mini server" - including its data.

Thanks to that, the next time we run:

docker-compose up -d

It will create the whole container from scratch: any data from before will be gone.

Booting isn't Instant

Let's see the whole process from the start. First, run:

docker-compose down

to stop and destroy the container. If we try to connect to MySQL now it, of course, fails. Now run:

docker-compose up -d

To start the container. Let's check on the process:

docker-compose ps

Ah! Look at that port! It was 32773 the first time we ran it. Now the container is exposed on port 32775. Let's try connecting:

mysql -u root --password=password --host=127.0.0.1 --port=32775

And... oh! It didn't work!

Lost connection to MySQL server

Ah. The truth is that, even though it looks like docker-compose up is instant, in reality, it takes a few seconds for MySQL to truly start. Eventually if we try again...

mysql -u root --password=password --host=127.0.0.1 --port=32775

Yes! We are in! But you won't see the docker_coolness database that we created earlier because docker-compose down destroyed our data.

At this point, we've created a docker-compose.yaml file and used docker-compose to launch a MySQL container that we can talk to. Awesome!

To connect to this from our Symfony app, all we need to do is update the DATABASE_URL environment variable to use the right password and port.

But... we're not going to do that. It would work... but it turns out that our app is already aware of the correct DATABASE_URL value... even though we haven't configured anything. Let's talk about how next.

Leave a comment!

26
Login or Register to join the conversation
Default user avatar
Default user avatar Rooarii MANUEL | posted 7 months ago

Hi there,
I'm trying to change the variable MYSQL_ROOT_PASSWORD
MYSQL_ROOT_PASSWORD: password
Unfortunately i can't access the database when i set to another value.
I have create the docker-compose.yml via

bin/console make:docker:database


here is my docker-compose.yml


version: "3.8"
services:

database:
image: 'mysql:latest'
container_name: '${DATABASE_NAME}'
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: '${DATABASE_ROOT_USER_PWD}'
MYSQL_DATABASE: '${DATABASE_NAME}'
ports:
# To allow the host machine to access the ports below, modify the lines below.
# For example, to allow the host to connect to port 3306 on the container, you would change
# "3306" to "3306:3306". Where the first port is exposed to the host and the second is the container port.
# See https://docs.docker.com/compose/compose-file/#ports for more information.
- '3306'

and my .env


# ...

###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=5.7&charset=utf8mb4"
#DATABASE_URL="mysql://root:R2OAR2I@127.0.0.1:3306/animals?serverVersion=5.7&charset=utf8mb4"
#DATABASE_URL="postgresql://symfony:ChangeMe@127.0.0.1:5432/app?serverVersion=13&charset=utf8"
###< doctrine/doctrine-bundle ###

DATABASE_NAME=test
DATABASE_ROOT_USER_PWD=test


Any ideas why setting a new root password doesn't work?

2 Reply

Hey Rooarii,

Looks like you're trying to set DATABASE_NAME and DATABASE_ROOT_USER_PWD while you have DATABASE_URL. They are incompatible with each others IIRC, so I'd recommend you to change password in the DATABASE_URL and drop all other "DATABASE_*" env vars you add below. Basically, if you need to change password to "test", do this:

DATABASE_URL="mysql://db_user:test@127.0.0.1:3306/db_name?serverVersion=5.7&charset=utf8mb4"

I.e. please, change the DATABASE_URL instead. Also, use symfony CLI command to boot the website, i.e. call: "symfony console" instead of "bin/console" - Symfony CLI will set up Docker env vars for you.

I hope this helps!

Cheers!

Reply

Hello,

I'm working on a mac, using Docker Desktop.

I downloaded the "finish" project.

I run :

$ docker-compose up -d

The composer image build correctly. I can see the logs on my terminal, and even the containers buing built on the Docker Desktop.

I can even do $ docker-compose ps and see my container running :

NAME                COMMAND                  SERVICE             STATUS              PORTS
finish-database-1   "docker-entrypoint.s…"   database            running             33060/tcp, 0.0.0.0:58553->3306/tcp

I start the symfony server $ symfony server:start -d without any issue.

Now let's run $ symfony var:export --multiline --vv (I add the "vv" to have see any issue), and then ... surprise :

30/10 09:45:07 WARNING   symfony  Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
export SYMFONY_APPLICATION_DEFAULT_ROUTE_HOST=127.0.0.1:8001
export SYMFONY_APPLICATION_DEFAULT_ROUTE_PATH=/
export SYMFONY_APPLICATION_DEFAULT_ROUTE_PORT=8001
export SYMFONY_APPLICATION_DEFAULT_ROUTE_SCHEME=https
export SYMFONY_APPLICATION_DEFAULT_ROUTE_URL=https://127.0.0.1:8001/
export SYMFONY_DEFAULT_ROUTE_HOST=127.0.0.1:8001
export SYMFONY_DEFAULT_ROUTE_PATH=/
export SYMFONY_DEFAULT_ROUTE_PORT=8001
export SYMFONY_DEFAULT_ROUTE_SCHEME=https
export SYMFONY_DEFAULT_ROUTE_URL=https://127.0.0.1:8001/
export SYMFONY_DOCKER_ENV=
export SYMFONY_PROJECT_DEFAULT_ROUTE_HOST=127.0.0.1:8001
export SYMFONY_PROJECT_DEFAULT_ROUTE_PATH=/
export SYMFONY_PROJECT_DEFAULT_ROUTE_PORT=8001
export SYMFONY_PROJECT_DEFAULT_ROUTE_SCHEME=https
export SYMFONY_PROJECT_DEFAULT_ROUTE_URL=https://127.0.0.1:8001/
export SYMFONY_TUNNEL=
export SYMFONY_TUNNEL_ENV=

Symfony CLI seems to not to be able to get the Docker API & extract the VARS as it supposed to do ... So can't run the project.

Can you help me find a solution ?

Thank you.

Reply

Hi,

Are you using native macos terminal? or bundled in PHPStorrm to run docker? Have you tried to run the container from Docker desktop, and after few minutes check Symfony CLI?

Cheers!

Reply

Hello. I used the PHPStorm terminal. But I tried with the native terminal, and it doesn't change anything.

I just used the native terminal to start again the Symfony server. Waited for 5 minutes, then run the symfony var:export, still the same error.

Reply

ok and does /var/run/docker.sock file exists? probably a permission issue for example if your docker is running under another user. or maybe docker.sock is located somewhere in another folder

Reply

Actually, StackOverflow found the solution for me.

When you install Docker Desktop for Mac, it will install an old version of docker-machine, that is not exposing any API.

You have to uninstall docker desktop manually, also docker-image, and they, you should resintall docker via brew (as a cask).

It will reinstall docker, docker-machine & even docker desktop with the new version of docker-machine that is exposing its API.

Working fine now :)

Thank you !

1 Reply

That's pretty interesting because I have docker installed on mac and it was installed via installer not brew

Reply
Maciej J. Avatar
Maciej J. Avatar Maciej J. | posted 3 months ago

Hello, my cli generates hashtags instead of asterisks in annotations, is there a way to change/configure that somewhere?

Reply
Tien dat L. Avatar
Tien dat L. Avatar Tien dat L. | posted 7 months ago

Hi, I'm having issues connecting to mysql :


mysql -u symfony --password=ChangeMe --host=127.0.0.1 --port=52883
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

docker-compose ps
start_database_1 docker-entrypoint.sh postgres Up 0.0.0.0:52883->5432/tcp

my .env
DATABASE_URL="postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=13&charset=utf8"

docker-compose.yml von recipes
version: '3'

services:
###> doctrine/doctrine-bundle ###
database:
image: postgres:${POSTGRES_VERSION:-13}-alpine
environment:
POSTGRES_DB: ${POSTGRES_DB:-app}
# You should definitely change the password in production
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-ChangeMe}
POSTGRES_USER: ${POSTGRES_USER:-symfony}
volumes:
- db-data:/var/lib/postgresql/data:rw
# You may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
# - ./docker/db/data:/var/lib/postgresql/data:rw
###< doctrine/doctrine-bundle ###

volumes:
###> doctrine/doctrine-bundle ###
db-data:
###< doctrine/doctrine-bundle ###

how can i fix them

Reply
Pieter-jan C. Avatar
Pieter-jan C. Avatar Pieter-jan C. | posted 1 year ago

For those not using Docker
In terminal set your mysql path to your installation of mysql
set path=%PATH%;C:\xampp\mysql\bin;
And then you can continue with the course
The standard port for xampp or mamp = 3306
mysql -u root --password=root--host=127.0.0.1 --port=3306

Reply

Hey ZoeF,

Thank you for sharing this information with others!

Cheers!

Reply
Farshad Avatar
Farshad Avatar Farshad | posted 1 year ago

Is it possible to skip docker or docktrine completely using Symfony? I like the Symfony structure and Twig, but for now I'd like to just connect with my MySQL Database and use PDO.

Reply

Hey Farry7,

Yes, sure! Docker and Doctrine are completely different things. You can avoid using Docker and connect to your local MySQL DB directly from your application. About Doctrine - yes, some websites even don't have a DB and works great too :) Just configure the PDO connection and use it directly instead.

Though I suppose, about Doctrine you mean Doctrine ORM, but Doctrine also has their own abstraction layer around PDO called Doctrine DBAL. I'd still recommend you look at it instead of working with PDO directly. Doctrine DBAL works almost the same way, it's a low level interface, but it's more flexible and has some nice features, you can check it out here: https://www.doctrine-projec...

Cheers!

1 Reply
Default user avatar
Default user avatar Vojtěch Janoušek | posted 1 year ago

Hi everybody, I have problem. I dont get name of database after I wrote:SHOW DATABASES. I get just arrows..... Do you have idea where is problem?

bruch@bruch-Latitude-E6520:~/Stažené/code-symfony-doctrine/start$ sudo docker-compose ps
Name Command State Ports
-------------------------------------------------------------------------------------------
start_database_1 docker-entrypoint.sh mysqld Up 0.0.0.0:32768->3306/tcp, 33060/tcp
bruch@bruch-Latitude-E6520:~/Stažené/code-symfony-doctrine/start$ sudo mysql -u root --password=password --host=127.0.0.1 --port=32768
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.22 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SHOW DATABASES
->
->
Reply

Hey Vojtěch,

Ah, haha, I know this problem :p You just need to add semicolon after *every* command :) So, literally, try "SHOW DATABASES;"

Cheers!

Reply
Karim B. Avatar
Karim B. Avatar Karim B. | posted 2 years ago

Hi

I'm having issues connecting to mysql

any help ?

macbookpro@Leonardo cauldron_overflow % docker-compose exec database mysql -u root -password=password
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Reply
Karim B. Avatar

i run
docker-composer down -v
docker-composer up -d

and now i'm getting this error

macbookpro@Leonardo cauldron_overflow % docker-compose exec database mysql -u root -password=password
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

1 Reply

Hey Karim B.!

Hmm. What changes did you make to go from the "Access Denied" to the "Can't connect" error? The first one (access denied) actually seems a bit better :). It means that there was simply some problem with the password or credentials.

Also, to be sure, what does your docker-compose.yaml file look like?

Cheers!

Reply
Karim B. Avatar

hi there
here is the docker-compose.yaml file


version: '3.7'
services:
database:
image: 'mysql:latest'
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: main
ports:
- '3306'
Reply

Hey Karim B. !

Hmmm. Yea, there are no surprises with the docker-compose.yaml file - it looks simple and correct. Which error do you currently have - the "Access Denied" error or "Can't connect"? And what changes did you make to go from one error to the other?

Also, one other thing you can try is to "bash" into the container and then execute mysql from there. This won't make any difference (it won't suddenly work) but it may help debugging:


docker-compose exec database bash

After running this, your terminal will be inside the container. You can then try the mysql commands directly. For example, for me (since I don't have the same problem as you), I can run:


mysql -u root --password=password

And this will connect me to the database. As I mentioned, you'll probably still get an error, but you can then mess around with different options:


mysql -u root --password=password --host=127.0.0.1
mysql -u root --host=127.0.0.1

Let me know what you find out!

Cheers!

Reply
Jewel F. Avatar
Jewel F. Avatar Jewel F. | posted 2 years ago

Hi,
I can't talk with mysql, where I have installed mysql locally. But app shows error I have added below:-

$ mysql -u root --password=123456 --host=127.0.0.1 --port=32768
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (10061)

I have changed mysql root password to 123456 because of my #mysql root password is 123456.

Reply

Jewel F.

hmm, that's interesting, is the service up and running? run service mysql status (the command depends on your OS). Also, double-check that the port is correct, and, just in case, try with localhost instead of 127.0.0.1

Reply
Mehul-J Avatar

thanks

Reply
Jewel F. Avatar
Jewel F. Avatar Jewel F. | MolloKhan | posted 2 years ago | edited

MolloKhan

service mysql status -> shows bash: service command not found
and the using of localhost instead of 127.0.0.1 it creates a still situation, which is not Hang but not doing anything. And when I write "exit" command on terminal it can exit from this situation.

Here is a screenshot link: https://snipboard.io/Xr124x...

Reply

> service mysql status -> shows bash: service command not found
Try with /etc/init.d/mysql status of look for the command that does it on your OS

> and the using of localhost instead of 127.0.0.1 it creates a still situation, which is not Hang but not doing anything. And when I write "exit" command on terminal it can exit from this situation.
Interesting... try it again but without specifying host and port so it uses the default ones

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial also works great for Symfony 6!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.4.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "doctrine/doctrine-bundle": "^2.1", // 2.1.1
        "doctrine/doctrine-migrations-bundle": "^3.0", // 3.0.2
        "doctrine/orm": "^2.7", // 2.8.2
        "knplabs/knp-markdown-bundle": "^1.8", // 1.9.0
        "knplabs/knp-time-bundle": "^1.11", // v1.16.0
        "sensio/framework-extra-bundle": "^6.0", // v6.2.1
        "sentry/sentry-symfony": "^4.0", // 4.0.3
        "stof/doctrine-extensions-bundle": "^1.4", // v1.5.0
        "symfony/asset": "5.1.*", // v5.1.2
        "symfony/console": "5.1.*", // v5.1.2
        "symfony/dotenv": "5.1.*", // v5.1.2
        "symfony/flex": "^1.3.1", // v1.17.5
        "symfony/framework-bundle": "5.1.*", // v5.1.2
        "symfony/monolog-bundle": "^3.0", // v3.5.0
        "symfony/stopwatch": "5.1.*", // v5.1.2
        "symfony/twig-bundle": "5.1.*", // v5.1.2
        "symfony/webpack-encore-bundle": "^1.7", // v1.8.0
        "symfony/yaml": "5.1.*", // v5.1.2
        "twig/extra-bundle": "^2.12|^3.0", // v3.0.4
        "twig/twig": "^2.12|^3.0" // v3.0.4
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.3", // 3.4.0
        "symfony/debug-bundle": "5.1.*", // v5.1.2
        "symfony/maker-bundle": "^1.15", // v1.23.0
        "symfony/var-dumper": "5.1.*", // v5.1.2
        "symfony/web-profiler-bundle": "5.1.*", // v5.1.2
        "zenstruck/foundry": "^1.1" // v1.5.0
    }
}