How to get Media entity image (Entity Reference Field) URL in TWIG theme
If this entity referenced image is controlled by Media, then you should let normal rendering occur:

{{ content.field_image2 }}


The rendering is then controlled by the field formatter, which will look to a display mode in Media, which is not dissimilar from Node display modes (default, teaser, etc).

Your filename would be something like:

media--media-bundle--display-mode.html.twig
media--media-bundle.html.twig


The first one is most specific, the second one would be the base for that media entity wherever it is used. I usually opt for the first one.

It is in this specific twig template where that code should live. The markup should be sourced there, instead of the referencing entity, in my opinion.

You could also do some preprocessing to solve this as well. Here is an example:

/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&amp;$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node-&gt;bundle();

  if ($bundle == 'landing_page' &amp;&amp; $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node-&gt;get('field_hero_image')-&gt;getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('landing_page_hero')-&gt;buildUrl($entity-&gt;field_image-&gt;entity-&gt;getFileUri());
    }
  }
}


Then in my respective template...

&lt;div{{ attributes.addClass(classes) }} style="background-image: url('{{ hero_image }}');"&gt;&lt;/div&gt;


Alternatively, you can preprocess the media entity:

/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&amp;$variables) {
  /** @var \Drupal\media_entity\MediaInterface $media */
  $media = $variables['elements']['#media'];

  $variables['media'] = $media;
  $variables['name'] = $media-&gt;label();

  // Helpful $content variable for templates.
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  $variables['attributes']['class'][] = 'media';
  $variables['attributes']['class'][] = Html::getClass('media-' . $media-&gt;bundle());

  if (!$media-&gt;isPublished()) {
    $variables['attributes']['class'][] = 'unpublished';
  }

  if ($variables['elements']['#view_mode']) {
    $variables['attributes']['class'][] = Html::getClass('view-mode-' . $variables['elements']['#view_mode']);

    if ($variables['elements']['#view_mode'] == 'hero') {
      $variables['hero_image'] = ImageStyle::load('hero')-&gt;buildUrl($media-&gt;field_image-&gt;entity-&gt;getFileUri());
    }
  }
}