Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Docker & Environment Variables

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 now have a Postgres database running inside of a Docker container. We can see it by running:

docker-compose ps

This also tells us that if we want to talk to this database, we can connect to port 50739 on our local machine. That will be a different port for you, because it's randomly chosen when we start Docker.

We also learned that we can talk to the database directly via:

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

To get our actual application to point to the database that's running on this port, we could go into .env or .env.local and customize DATABASE_URL accordingly: with user symfony password ChangeMe... and with whatever your port currently is. Though... we would need to update that port each time we start and stop Docker.

Symfony Binary & Docker Env Vars

Thankfully, we don't need to do any of that because, surprise, the DATABASE_URL environment variable is already being correctly set! When we set up our project, we started a local dev server using the Symfony binary.

Just as a reminder, I'm going to run:

symfony server:stop

to stop that server. And then restart it with:

symfony serve -d

I'm mentioning this because the symfony binary has a pretty awesome Docker superpower.

Watch: when you refresh now... and hover over the bottom right corner of the web debug toolbar, it says "Env Vars: From Docker".

In short, the Symfony binary noticed that Docker was running and exposed some new environment variables pointing to the database! I'll show you. Open up public/index.php.

10 lines public/index.php
... lines 1 - 2
use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};

We don't normally care about this file... but it's a great spot to dump some info right when our app starts booting. Inside the callback, dd() the $_SERVER superglobal. That variable contains a lot of information, including any environment variables.

Ok, spin over and refresh. Big list! Search for DATABASE_URL and... there it is! But that is not the value that we have in our .env file: the port is not what we have there. Nope, it's the correct port needed to talk to the Docker container!

Yup, the Symfony binary detects that Docker is running and sets a real DATABASE_URL environment variable that points to that container. And remember, since this is a real environment variable, it will win over any value placed in the .env or .env.local files.

The point is: just by starting Docker, everything is already set up: we didn't need to touch any config files. That's pretty cool.

By the way, if you want to see all the environment variables the Symfony binary is setting, you can run:

symfony var:export --multiline

But the most important one by far is DATABASE_URL.

Ok: Doctrine is configured! Next, let's create the database itself via a bin/console command. When we do that, we'll learn a trick for doing this with the environment variables from the Symfony binary.

Leave a comment!

22
Login or Register to join the conversation
ling Avatar
ling Avatar ling | posted 1 month ago | 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

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 1 month ago | 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 1 month ago | 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 8 months ago | 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

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 7 months ago | 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 1 year ago

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