Chapters
-
Course Code
Subscribe to download the code!
Subscribe to download the code!
-
This Video
Subscribe to download the video!
Subscribe to download the video!
-
Subtitles
Subscribe to download the subtitles!
Subscribe to download the subtitles!
-
Course Script
Subscribe to download the script!
Subscribe to download the script!
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
Muy bien, ¡ya tenemos Doctrine instalado! Pero ahora necesitamos, ya sabes, poner en marcha un servidor de base de datos.
DATABASE_URL
Variable de entorno
Echa un vistazo a nuestro archivo .env
. Cuando instalamos Doctrine, la receta Flex añadió esta sección doctrine-bundle. La variable de entornoDATABASE_URL
es donde le decimos a Doctrine cómo conectarse a nuestra base de datos. Es una cadena especial con aspecto de URL llamada DSN, si quieres un poco de terminología friki.
Contiene el tipo de base de datos a la que nos estamos conectando -mysql
, postgres
, sqlite
, borgsql
, etc, un nombre de usuario, contraseña, host, puerto y el nombre de la base de datos. Cualquier parámetro de consulta es una configuración extra.
Por defecto, DATABASE_URL
está configurado para conectarse a una base de datos Postgres y eso es lo que utilizaremos. Lo pondremos en marcha muy fácilmente con Docker.
Si no quieres utilizar Docker, ¡no hay problema! Comenta esta línea y descomenta la desqlite
. SQLite no requiere un servidor: es sólo un archivo en tu sistema de archivos. Como Doctrine abstrae la capa de base de datos, en su mayor parte, el código que escribamos funcionará con cualquier tipo de base de datos. ¡Genial!
Recuerda, no guardes ninguna información sensible en este archivo: está comprometido en tu repositorio. Si tienes tu propio servidor de base de datos localmente, crea un archivo .env.local
(Git lo ignora), y establece allí tu propio DATABASE_URL
.
Iniciar un contenedor Postgres con Docker
Vale, ¿cómo podemos poner en marcha un servidor de base de datos Postgres?
Echa un vistazo a compose.yaml
. Lo ha añadido una receta de Flex y contiene la configuración de Docker, incluido este servicio database
para poner en marcha un contenedor Postgres ¡Fantástico! Puedes hacer lo que quieras, pero nosotros sólo vamos a utilizar Docker como una forma cómoda de ejecutar localmente un servidor de base de datos. El propio PHP está instalado normalmente en mi máquina.
Abre tu terminal y ejecuta:
docker compose up -d
Esto inicia los contenedores Docker y -d
le dice a Docker que lo haga todo en segundo plano.
Pero, ¿dónde se ejecuta el servidor de bases de datos? ¿En qué puerto? ¿No necesitamos saberlo para poder actualizar DATABASE_URL
para que apunte a él?
¡La CLI de Symfony es genial!
No! El binario CLI de symfony
que está ejecutando el servidor web tiene algo de magia Docker! Salta y actualiza la aplicación. Aquí abajo, pasa el ratón sobre "Servidor". Contiene detalles sobre el servidor Symfony CLI. Esta parte significa que ha detectado automáticamente nuestros contenedores Docker y ha configurado las variables de entorno por nosotros
Tip
Para que la detección automática funcione, tu proyecto local tiene que ser un repositorio Git. Si sigues el código descargado, tendrás que inicializar uno con git init
.
Te lo mostraré. Ve a nuestro terminal y ejecuta:
symfony var:export --multiline
Esto nos muestra algunas variables de entorno adicionales que la CLI de Symfony está configurando para nosotros, además de las que aparecen en .env
.
Desplázate un poco hacia arriba para ver.... ¡Aquí está! DATABASE_URL
¡! Esto anula la que está en .env
y apunta a la base de datos Postgres que se ejecuta en Docker. Ese número de puerto cambiará aleatoriamente, pero la CLI de Symfony siempre utilizará el correcto.
symfony console
vs bin/console
Ahora, estamos acostumbrados a ejecutar los comandos de Symfony con bin/console
. Pero cuando utilizamos la CLI de Symfony con una base de datos Docker, necesitamos ejecutar los comandos específicos de la base de datos a través desymfony console
en su lugar. Es lo mismo que bin/console
, pero da a la CLI de Symfony la oportunidad de añadir las variables de entorno.
Crear la base de datos
Ya está El servidor de la base de datos se está ejecutando en un contenedor Docker y DATABASE_URL
está apuntando a él. Para crear la base de datos, ejecuta:
symfony console doctrine:database:create
¡Un error! ¡No te preocupes! El error nos está diciendo que la base de datos ya existe: aparentemente el servidor viene con una. Pero esto es bueno, ¡significa que nos estamos conectando a nuestro servidor de base de datos!
Bien, ya tenemos Doctrine y una base de datos. ¡Ahora necesitamos una tabla! Lo haremos a continuación saltando al mundo de las entidades y las migraciones.
20 Comments
Hey Nathan,
Thanks for sharing this edge case with others. Actually, I think I always work with projects that are already with initiated Git repo, so I haven't faced the problem you explained here. Though, for me it's weird that Docker compose does not work properly if you don't have .git/ folder, IMO Docker should not care about Git repo, it should care about the folder in which you're currently cd
-ed to. But I may be wrong, or maybe it depends on some special system settings. Anyway, maybe it will be useful for someone.
Cheers!
Yeah, I only didn't have it initialized because I had just downloaded the code here.
It's actually the Symfony CLI that uses the .git folder. It uses that to find the name of the directory that the project is in, and then looks for a Docker container running with the same name. No .git folder, Symfony CLI didn't detect the project name, and without the project name it didn't know which Docker container to connect to.
Someone opened a PR to the CLI to improve the directory detection just last week, actually 🙂
Hey Nathan,
Oh, I see it now! Yeah, I has probably never faced it because always have Git initialized, but when you download the course code - it makes sense there's no Git there, though it's a good idea to init it first.
Good catch actually! And thanks for sharing this with others, I didn't know about this behavior. It sounds like it should be fixed upstream to be more robust.
Cheers!


martin@martin-inspiron153530:~/Projects/starshop(master)$ symfony console doctrine:database:create
Could not create database "app" for connection named default
An exception occurred in the driver: could not find driver
martin@martin-inspiron153530:~/Projects/starshop(master)$ php -m | grep pdo
pdo_sqlite
martin@martin-inspiron153530:~/Projects/starshop(master)$ sudo apt install php-pgsql
[sudo] password for martin:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
php-pgsql is already the newest version (2:8.4+96+ubuntu24.04.1+deb.sury.org+1).
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.

Hey @Martin-C
Is your database server up and running?
Cheers!


okay, I've got it solved ... had to turn off docker compose running my other projects and work just with the startshop one. I haven't realized the other one is running and I had a lot of containers mixed up there. Now it's all fine.
Hey @Martin-C,
Glad you got it sorted. The Symfony CLI is usually smart enough to account for multiple containers but might have been some port duplication issues.
--Kevin


CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b1b2619ddf1b postgres:16-alpine "docker-entrypoint.s…" 3 days ago Up 3 days (healthy) 0.0.0.0:32772->5432/tcp, [::]:32772->5432/tcp starshop-database-1


Hi, yes it is...
sudo systemctl status postgresql
[sudo] password for martin:
postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: enabled)
Active: active (exited) since Thu 2025-05-29 14:04:24 CEST; 3 weeks 3 days ago
Main PID: 1769 (code=exited, status=0/SUCCESS) CPU: 1ms
may 29 14:04:24 martin-inspiron153530 systemd[1]: Starting postgresql.service - PostgreSQL RDBMS...
may 29 14:04:24 martin-inspiron153530 systemd[1]: Finished postgresql.service - PostgreSQL RDBMS.


in my case, there is no server tab in bottow right corner, only symfony

Hey @Martin-C,
That's weird. Are you on mobile, or perhaps the toolbar is not expanded?
Do you see any errors in the console?
Cheers!


okay, got it working ... I just had to restart symfony server


hi, this is the server status
martin@martin-inspiron153530:~/Projects/starshop(master)$ symfony server:status
Local Web Server
Listening on http://127.0.0.1:8001
The Web server is using PHP FPM 8.4.8 (from default version in $PATH)
Local Domains
Workers
PID 75896: symfony console tailwind:build --watch
PID 75887: /usr/bin/php8.3 -S 127.0.0.1:44845 -d variables_order=EGPCS /home/martin/.symfony5/php/8bebc3742d26aca368056064cc39b71a5694968f/8.3.21-router.php
Environment Variables
Exposed from Docker


When I set up everything and run "docker compose up -d" I get the "Container starshop-database-1 Started" response, however the Server tooltip shows docker as down ... which is different to what you are seeing.
Any suggestions?
Hey @John-B, what version of the Symfony CLI are you using? (symfony version
)


Symfony CLI 5.10.5
I see this issue looks similar. Does the workaround posted there help at all?


It's working now, thanks.
It was a permission issue ...
I had run docker compose with a "user" permission while symfony was served with "root" permissions.
I might have to restart the project with "user" permissions rather than "root" permissions to get around permission problems.
Initially I had forgot to modify the /var/www permissions to allow write for local users and just got around the issue using sudo ... silly me..
Awesome, I'm so happy this is resolved for you!

"Houston: no signs of life"
Start the conversation!
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": ">=8.2",
"ext-ctype": "*",
"ext-iconv": "*",
"babdev/pagerfanta-bundle": "^4.5", // v4.5.0
"doctrine/dbal": "^3", // 3.9.4
"doctrine/doctrine-bundle": "^2.13", // 2.13.2
"doctrine/doctrine-migrations-bundle": "^3.3", // 3.4.0
"doctrine/orm": "^3.3", // 3.3.1
"knplabs/knp-time-bundle": "^2.2", // v2.4.0
"pagerfanta/doctrine-orm-adapter": "^4.7", // v4.7.1
"php-cs-fixer/shim": "^3.46", // v3.65.0
"phpdocumentor/reflection-docblock": "^5.3", // 5.6.0
"phpstan/phpdoc-parser": "^1.25", // 1.33.0
"stof/doctrine-extensions-bundle": "^1.12", // v1.13.0
"symfony/asset": "7.1.*", // v7.1.6
"symfony/asset-mapper": "7.1.*", // v7.1.9
"symfony/console": "7.1.*", // v7.1.8
"symfony/dotenv": "7.1.*", // v7.1.9
"symfony/flex": "^2", // v2.4.7
"symfony/framework-bundle": "7.1.*", // v7.1.6
"symfony/http-client": "7.1.*", // v7.1.9
"symfony/monolog-bundle": "^3.0", // v3.10.0
"symfony/property-access": "7.1.*", // v7.1.6
"symfony/property-info": "7.1.*", // v7.1.9
"symfony/runtime": "7.1.*", // v7.1.7
"symfony/serializer": "7.1.*", // v7.1.9
"symfony/stimulus-bundle": "^2.13", // v2.22.0
"symfony/twig-bundle": "7.1.*", // v7.1.6
"symfony/ux-turbo": "^2.13", // v2.22.0
"symfony/yaml": "7.1.*", // v7.1.6
"symfonycasts/tailwind-bundle": "^0.7.1", // v0.7.1
"twig/extra-bundle": "^2.12|^3.0", // v3.16.0
"twig/twig": "^2.12|^3.0" // v3.16.0
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.6", // 3.7.1
"symfony/debug-bundle": "7.1.*", // v7.1.6
"symfony/maker-bundle": "^1.52", // v1.61.0
"symfony/stopwatch": "7.1.*", // v7.1.6
"symfony/web-profiler-bundle": "7.1.*", // v7.1.9
"zenstruck/foundry": "^2.2" // v2.3.1
}
}
So, I know that I should have followed the instructions exactly and checked the git diff, but I didn't think it would matter. In this case, it actually really does matter!
The automated detection of Docker was not working for me despite following the ticket mentioned in the other thread here in the comments. When I ran the
symfony var:export
command with the debug flag, it said it couldn't find my compose directory.The actual problem is that the compose directory is located by finding the
.git
directory that your terminal is currently inside of. When there is no git directory, it doesn't default to the directory you ran the command inside of or anything, it just doesn't know what directory to use. Because it doesn't know what directory to use, it can't look inside of Docker to see if there are any containers running.So, make sure you initialize a git repo if you download the source code and want to use the Docker compose project shown here 😅