diff --git a/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php b/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php
index 6b4ce17693e62f60c8f3e3ab51ffe9014492e48e..46fea2f830b1cd919002ac1f1313b7903982bc3a 100644
--- a/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php
+++ b/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php
@@ -383,10 +383,13 @@ protected function initUserSession() {
    */
   protected function initKernel(Request $request) {
     $this->kernel = DrupalKernel::createFromRequest($request, $this->classLoader, 'prod', TRUE);
-    $this->kernel->prepareLegacyRequest($request);
+
     // Force the container to be built from scratch instead of loaded from the
     // disk. This forces us to not accidentally load the parent site.
-    return $this->kernel->rebuildContainer();
+    $this->kernel->invalidateContainer();
+
+    $this->kernel->prepareLegacyRequest($request);
+    return \Drupal::getContainer();
   }
 
   /**
@@ -420,8 +423,8 @@ protected function installModulesFromClassProperty(ContainerInterface $container
         // The exception message has all the details.
         $this->fail($e->getMessage());
       }
-
-      $this->rebuildContainer();
+      // The container was already rebuilt by the ModuleInstaller.
+      $this->container = \Drupal::getContainer();
     }
   }