I'm trying to get the client IP in settings.php for security reasons, using the following code. I have to support X-Forwarded-For header because accessing web server over loadbalancer.

$clientIp = \Drupal::request()->getClientIp();

It causes the following error.

The website encountered an unexpected error. Please try again later.
Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/my-site/docroot/core/lib/Drupal.php).
Drupal::getContainer() (Line: 218)
Drupal::request() (Line: 759)
require('/var/www/my-site/docroot/sites/default/settings.php') (Line: 116) Drupal\Core\Site\Settings::initialize('/var/www/my-site/docroot', 'sites/default', Object) (Line: 1015)
Drupal\Core\DrupalKernel->initializeSettings(Object) (Line: 642)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Any suggestions to fix this?


1 Answer 1


In settings.php the drupal kernel is not loaded yet, so the service container is not initialized. Use the php superglobal $_SERVERinstead:

$client_ip = $_SERVER['REMOTE_ADDR'];
  • This is unreliable in itself .
    – Mike Q
    Commented Dec 12, 2018 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.