diff --git a/core/lib/Drupal/Core/Extension/ModuleInstaller.php b/core/lib/Drupal/Core/Extension/ModuleInstaller.php
index 2cf34bd22f..754be196c3 100644
--- a/core/lib/Drupal/Core/Extension/ModuleInstaller.php
+++ b/core/lib/Drupal/Core/Extension/ModuleInstaller.php
@@ -309,7 +309,11 @@ public function install(array $module_list, $enable_dependencies = TRUE) {
 
     // If any modules were newly installed, invoke hook_modules_installed().
     if (!empty($modules_installed)) {
-      \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.old'));
+      // If the container was rebuilt during hook_install() it might not have
+      // the 'router.route_provider.old' service.
+      if (\Drupal::hasService('router.route_provider.old')) {
+        \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.old'));
+      }
       if (!\Drupal::service('router.route_provider.lazy_builder')->hasRebuilt()) {
         // Rebuild routes after installing module. This is done here on top of
         // \Drupal\Core\Routing\RouteBuilder::destruct to not run into errors on
diff --git a/core/modules/system/tests/modules/module_test/module_test.install b/core/modules/system/tests/modules/module_test/module_test.install
index 5f3f6f654c..b76b7936f5 100644
--- a/core/modules/system/tests/modules/module_test/module_test.install
+++ b/core/modules/system/tests/modules/module_test/module_test.install
@@ -34,4 +34,9 @@ function module_test_install() {
       'data' => $schema['fields']['data']['type'],
     ])
     ->execute();
+  if (\Drupal::state()->get('module_test_install:rebuild_container')) {
+    // Ensure that the container can be rebuilt during hook_install(). Doing
+    // this in hook_install() is bad practice but it should not break anything.
+    \Drupal::service('kernel')->rebuildContainer();
+  }
 }
diff --git a/core/tests/Drupal/KernelTests/Core/Extension/ModuleInstallerTest.php b/core/tests/Drupal/KernelTests/Core/Extension/ModuleInstallerTest.php
index ff183c6f00..7ffe65c9fc 100644
--- a/core/tests/Drupal/KernelTests/Core/Extension/ModuleInstallerTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Extension/ModuleInstallerTest.php
@@ -85,4 +85,13 @@ public function testCacheBinCleanup() {
     $this->assertFalse($schema->tableExists($table));
   }
 
+  /**
+   * Ensure that rebuilding the container in hook_install() works.
+   */
+  public function testKernelRebuildDuringHookInstall() {
+    \Drupal::state()->set('module_test_install:rebuild_container', TRUE);
+    $module_installer = $this->container->get('module_installer');
+    $this->assertTrue($module_installer->install(['module_test']));
+  }
+
 }
