Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Docker y variables de entorno

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.

Ahora tenemos una base de datos Postgres ejecutándose dentro de un contenedor Docker. Podemos verlo ejecutando:

docker-compose ps

Esto también nos dice que si queremos hablar con esta base de datos, podemos conectarnos al puerto50739 en nuestra máquina local. Ese será un puerto diferente para ti, porque se elige al azar cuando iniciamos Docker.

También hemos aprendido que podemos hablar con la base de datos directamente a través de:

docker-compose exec database psql --user symfony --password app

Para conseguir que nuestra aplicación real apunte a la base de datos que se ejecuta en este puerto, podríamos entrar en .env o .env.local y personalizar DATABASE_URLen consecuencia: con el usuario symfony la contraseña ChangeMe... y con el puerto que tengas actualmente. Aunque... tendríamos que actualizar ese puerto cada vez que iniciemos y detengamos Docker.

El Binario de Symfony y variables de entorno de Docker

Afortunadamente, no tenemos que hacer nada de eso porque, sorpresa, ¡la variable de entorno DATABASE_URLya está correctamente configurada! Cuando configuramos nuestro proyecto, iniciamos un servidor local de desarrollo utilizando el binario de Symfony.

Como recordatorio, voy a ejecutar

symfony server:stop

para detener ese servidor. Y luego reiniciarlo con:

symfony serve -d

Menciono esto porque el binario symfony tiene un superpoder de Docker bastante impresionante.

Observa: cuando actualices ahora... y pases el ratón por la esquina inferior derecha de la barra de herramientas de depuración de la web, dirá "Env Vars: De Docker".

En resumen, ¡el binario de Symfony se dio cuenta de que Docker se estaba ejecutando y expuso algunas nuevas variables de entorno que apuntaban a la base de datos! Te lo mostraré. Abrepublic/index.php. Normalmente no nos preocupamos por este archivo... pero es un buen lugar para volcar algo de información justo cuando nuestra aplicación empieza a arrancar. Dentro de la llamada de retorno,dd() la superglobal $_SERVER. Esa variable contiene mucha información, incluyendo cualquier variable de entorno.

Bien, gira y actualiza. ¡Una gran lista! Busca DATABASE_URL y... ¡ahí está! Pero ese no es el valor que tenemos en nuestro archivo .env: el puerto no es el que tenemos ahí. No, ¡es el puerto correcto necesario para hablar con el contenedor Docker!

Sí, el binario de Symfony detecta que Docker se está ejecutando y establece una variable de entorno realDATABASE_URL que apunta a ese contenedor. Y recuerda que, al tratarse de una variable de entorno real, ganará a cualquier valor colocado en los archivos .env o .env.local.

La cuestión es que, con sólo iniciar Docker, ya está todo configurado: no hemos tenido que tocar ningún archivo de configuración. Eso está muy bien.

Por cierto, si quieres ver todas las variables de entorno que configura el binario de Symfony, puedes ejecutarlo:

symfony var:export --multiline

Pero por mucho la más importante es DATABASE_URL.

Bien: ¡Doctrine está configurado! A continuación, vamos a crear la base de datos propiamente dicha mediante un comando bin/console. Cuando lo hagamos, aprenderemos un truco para hacerlo con las variables de entorno del binario de Symfony.

Leave a comment!

22
Login or Register to join the conversation
ling Avatar
ling Avatar ling | posted hace 1 mes | edited

I don't have this super power of symfony console directly creating the docker friendly ENV vars.
I'm using php FPM 8.2.5 and symfony 6.1.2 (on Mac 12.6.6).
Don't know if it's normal (i.e., a change in symfony or doctrine behaviour with the newer versions), or if it's specific to my computer, but in the meantime i'll just create an .env.local file with DATABASE_URL using the correct docker port, hoping that it will do for the rest of this course.

Here is my compose.json in case it helps:

{
    "type": "project",
    "license": "proprietary",
    "prefer-stable": true,
    "require": {
        "php": ">=8.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "doctrine/doctrine-bundle": "^2.10",
        "doctrine/doctrine-migrations-bundle": "^3.2",
        "doctrine/orm": "^2.15",
        "knplabs/knp-time-bundle": "^1.18",
        "symfony/asset": "6.1.*",
        "symfony/console": "6.1.*",
        "symfony/dotenv": "6.1.*",
        "symfony/flex": "^2",
        "symfony/framework-bundle": "6.1.*",
        "symfony/http-client": "6.1.*",
        "symfony/monolog-bundle": "^3.0",
        "symfony/runtime": "6.1.*",
        "symfony/twig-bundle": "6.1.*",
        "symfony/ux-turbo": "^2.0",
        "symfony/webpack-encore-bundle": "^1.13",
        "symfony/yaml": "6.1.*",
        "twig/extra-bundle": "^2.12|^3.0",
        "twig/twig": "^2.12|^3.0"
    },
    "config": {
        "allow-plugins": {
            "composer/package-versions-deprecated": true,
            "symfony/flex": true,
            "symfony/runtime": true
        },
        "optimize-autoloader": true,
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true,
        "platform": {}
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php72": "*",
        "symfony/polyfill-php73": "*",
        "symfony/polyfill-php74": "*",
        "symfony/polyfill-php80": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "6.1.*",
            "docker": true
        }
    },
    "require-dev": {
        "symfony/debug-bundle": "6.1.*",
        "symfony/maker-bundle": "^1.41",
        "symfony/stopwatch": "6.1.*",
        "symfony/web-profiler-bundle": "6.1.*"
    }
}
1 Reply
Lore Avatar

Same problem

Reply
MolloKhan Avatar MolloKhan | SFCASTS | Lore | posted hace 1 mes | edited

Hey @Lore

I strongly recommend installing Symfony CLI, it will make your life way easier, but if for some reason that's not possible, you'll have to go with ling's approach

Cheers!

Reply
Lore Avatar

Thanks, I've already installed Symfony CLI, launched the 'docker-compose up -d' command, and subsequently, the 'symfony serve -d' command, but in the debug toolbar, 'docker compose' shows 'down,' and 'Env var' shows 'none.'

Reply

That's unexpected, Symfony CLI should detect your Docker configuration automatically. Check two things
1) Your Symfony project is using Symfony Flex. You should see symfony/flex inside your composer.json file
2) Your docker-compose.yaml file should be at the root of your project, otherwise you need to set up a few env vars as explained here https://symfony.com/doc/current/setup/symfony_server.html#docker-integration

Reply
sadikoff Avatar sadikoff | SFCASTS | ling | posted hace 1 mes | edited

Hey @ling

Yeah, you can just use .env files to configure your environment. But why you can't use the symfony binary with docker detection?

Cheers!

Reply
ling Avatar
ling Avatar ling | sadikoff | posted hace 1 mes | edited

I don't know, it just doesn't hook up naturally. I followed all the steps of the tutorials i believe. Not sure why it's not working. I could follow the two previous courses without any problem, this is the first time the code doesn't seem to work as it does in the video. When i hover on the right-bottom corner of the debug bar, it says that docker-compose is down, and next to ENV variables it shows: NONE. But i have a docker container with psql in it, and i ran symfony serve. Mystic?

1 Reply

I guess something is wrong with docker detection, is it the latest version? Which console is used to run docker? Symfony binary? I'm asking because I had same issues when tried to run docker from the PHPStorm console, and for me, it works if I run docker from the native MacOS console or from the docker desktop app.

Cheers

Reply
ling Avatar

Not sure how closely your issues are related to mine.
But if it helps, here is my final composer.json (i fought a lot with it because some tools in the whole tutorial had some compatibility issues):

{

"type": "project",
"license": "proprietary",
"prefer-stable": true,
"require": {
	"php": ">=8.1",
	"ext-ctype": "*",
	"ext-iconv": "*",
	"babdev/pagerfanta-bundle": "^4.2",
	"doctrine/doctrine-bundle": "^2.10",
	"doctrine/doctrine-migrations-bundle": "^3.2",
	"doctrine/orm": "^2.15",
	"knplabs/knp-time-bundle": "^1.20",
	"pagerfanta/doctrine-orm-adapter": "^4.2",
	"pagerfanta/twig": "^4.2",
	"sensio/framework-extra-bundle": "^6.2",
	"stof/doctrine-extensions-bundle": "^1.8",
	"symfony/asset": "6.2.*",
	"symfony/cache": "^6.2",
	"symfony/config": "^6.2",
	"symfony/console": "6.2.*",
	"symfony/dependency-injection": "^6.2",
	"symfony/dotenv": "6.2.*",
	"symfony/flex": "^2",
	"symfony/framework-bundle": "6.2.*",
	"symfony/http-client": "6.2.*",
	"symfony/http-foundation": "6.2.*",
	"symfony/http-kernel": "^6.2",
	"symfony/monolog-bundle": "^3.0",
	"symfony/property-access": "^6.2",
	"symfony/routing": "6.2.*",
	"symfony/runtime": "6.2.*",
	"symfony/translation": "6.2.*",
	"symfony/twig-bridge": "6.2.*",
	"symfony/twig-bundle": "6.2.*",
	"symfony/ux-turbo": "^2.0",
	"symfony/webpack-encore-bundle": "^1.13",
	"symfony/yaml": "6.2.*",
	"twig/extra-bundle": "^2.12|^3.0",
	"twig/twig": "^2.12|^3.0"
},
"config": {
	"allow-plugins": {
		"composer/package-versions-deprecated": true,
		"symfony/flex": true,
		"symfony/runtime": true
	},
	"optimize-autoloader": true,
	"preferred-install": {
		"*": "dist"
	},
	"sort-packages": true,
	"platform": {}
},
"autoload": {
	"psr-4": {
		"App\\": "src/"
	}
},
"autoload-dev": {
	"psr-4": {
		"App\\Tests\\": "tests/"
	}
},
"replace": {
	"symfony/polyfill-ctype": "*",
	"symfony/polyfill-iconv": "*",
	"symfony/polyfill-php72": "*",
	"symfony/polyfill-php73": "*",
	"symfony/polyfill-php74": "*",
	"symfony/polyfill-php80": "*"
},
"scripts": {
	"auto-scripts": {
		"cache:clear": "symfony-cmd",
		"assets:install %PUBLIC_DIR%": "symfony-cmd"
	},
	"post-install-cmd": [
		"@auto-scripts"
	],
	"post-update-cmd": [
		"@auto-scripts"
	]
},
"conflict": {
	"symfony/symfony": "*"
},
"extra": {
	"symfony": {
		"allow-contrib": true,
		"require": "6.1.*",
		"docker": true
	}
},
"require-dev": {
	"doctrine/doctrine-fixtures-bundle": "^3.4",
	"symfony/debug-bundle": "6.1.*",
	"symfony/maker-bundle": "^1.41",
	"symfony/stopwatch": "6.1.*",
	"symfony/web-profiler-bundle": "6.1.*",
	"zenstruck/foundry": "^1.34"
}

}

I'm using Docker desktop version 4.19.0.
I start the project with docker:

docker compose up -d

Then the symfony server:

symfony serve -d

[OK] Web server listening

  The Web server is using PHP FPM 8.2.5                                                                             
  https://127.0.0.1:8000   

The opening the website at https://127.0.0.1:8000, the bottom right corner of the debug bar shows:

sf 6.2.12, and opening the sf server hover menu, i still have:

  • docker compose: down
  • env vars: none

which is easily fix by setting the correct port for the DATABASE_URL variable in an env.local file as mentioned in a video of the tutorial.
So i'm not sure where the problem is exactly, but the workaround is fine by me as i just wanted to complete the tutorial, knowing that in prod env there are always other things we can do to setup env variables...

Reply

hm Symfony binary version?

Reply
ling Avatar
$ php bin/console --version
Symfony 6.2.12 (env: dev, debug: true) #StandWithUkraine https://sf.to/ukraine
Reply

nope, the binary version symfony version ?

Reply
ling Avatar
$ symfony version
Symfony CLI version 5.5.6 (c) 2021-2023 Fabien Potencier #StandWithUkraine Support Ukraine (2023-05-16T13:26:30Z - stable)
1 Reply

Sorry for long waiting, I tried to debug, different environments, but I can't reproduce this situation, so probably I don't have any solution for it. Looks like Symfony binary just didn't catch docker instance to get all env vars

Cheers

Reply
Algirdas Avatar
Algirdas Avatar Algirdas | posted hace 8 meses | edited

Hello, having issues making Symfony see my docker.

Symfony is running. Docker is running.
But when I open localhost server does not see my database running and DATABASE_URL port is not changed...

Not sure what is the issue

Docker version 20.10.17, build 100c701
Using Ubuntu

In next tutorial video I tried running: ./bin/console doctrine:database:create
And I got this:
An exception occurred in the driver: could not find driver

Reply

Hey Algirdas,

When you use Docker + Symfony, you got to run any commands through the Symfony CLI. For example symfony console doctrine:database:create or to spin up the web server symfony serve -d

I hope it helps. Cheers!

1 Reply
ling Avatar

Is there any difference between using
php bin/console and symfony console
? Or is it exactly the same ?

Reply
MolloKhan Avatar MolloKhan | SFCASTS | ling | posted hace 1 mes | edited

Hey @ling

It has a few subtle differences. If you use Docker, you can execute your commands through Symfony CLI to let it set up all of the env vars. Also, you can configure what PHP version you want to use per project, you can read more about it here: https://symfony.com/doc/current/setup/symfony_server.html#selecting-a-different-php-version

Cheers!

1 Reply
Algirdas Avatar
Algirdas Avatar Algirdas | MolloKhan | posted hace 7 meses | edited

Hi, so not sure what fixed it. Today I tried launching and had issues connecting to database not to mention the issue I already had. Reinstalled postgresql on my machine and now it works

Reply

Hey Algirdas!

Weird! Database gremlins hiding somewhere :). Anyways, I'm glad it's behaving for you now!

Cheers!

Reply
mofogasy Avatar
mofogasy Avatar mofogasy | posted hace 1 año

Hi,
are you planning to make a video on how to dockerise the full app ie database + php + web server ?

I am struggling with docker configs

Reply

Hey mofogasy

There is no plan to make a tutorial about it soon but thank you for telling us what you would like to learn. We take in consideration all feedback when we select the topic of the next tutorial

Thanks!

Reply
Cat in space

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

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=8.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "babdev/pagerfanta-bundle": "^3.7", // v3.7.0
        "doctrine/doctrine-bundle": "^2.7", // 2.7.0
        "doctrine/doctrine-migrations-bundle": "^3.2", // 3.2.2
        "doctrine/orm": "^2.12", // 2.12.3
        "knplabs/knp-time-bundle": "^1.18", // v1.19.0
        "pagerfanta/doctrine-orm-adapter": "^3.6", // v3.6.1
        "pagerfanta/twig": "^3.6", // v3.6.1
        "sensio/framework-extra-bundle": "^6.2", // v6.2.6
        "stof/doctrine-extensions-bundle": "^1.7", // v1.7.0
        "symfony/asset": "6.1.*", // v6.1.0
        "symfony/console": "6.1.*", // v6.1.2
        "symfony/dotenv": "6.1.*", // v6.1.0
        "symfony/flex": "^2", // v2.2.2
        "symfony/framework-bundle": "6.1.*", // v6.1.2
        "symfony/http-client": "6.1.*", // v6.1.2
        "symfony/monolog-bundle": "^3.0", // v3.8.0
        "symfony/proxy-manager-bridge": "6.1.*", // v6.1.0
        "symfony/runtime": "6.1.*", // v6.1.1
        "symfony/twig-bundle": "6.1.*", // v6.1.1
        "symfony/ux-turbo": "^2.0", // v2.3.0
        "symfony/webpack-encore-bundle": "^1.13", // v1.15.1
        "symfony/yaml": "6.1.*", // v6.1.2
        "twig/extra-bundle": "^2.12|^3.0", // v3.4.0
        "twig/twig": "^2.12|^3.0" // v3.4.1
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4", // 3.4.2
        "symfony/debug-bundle": "6.1.*", // v6.1.0
        "symfony/maker-bundle": "^1.41", // v1.44.0
        "symfony/stopwatch": "6.1.*", // v6.1.0
        "symfony/web-profiler-bundle": "6.1.*", // v6.1.2
        "zenstruck/foundry": "^1.21" // v1.21.0
    }
}
userVoice