Skip to content

Commit f2788ea

Browse files
authored
Fixed dapr sidecar resolution when app in container (#1227)
- When the app is in a container we need to tell it to communicate over the container host instead of local host. Not all SDKs support this new env variable, but we set it anyways (.NET works).
1 parent a2e1d84 commit f2788ea

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

src/Aspire.Hosting.Dapr/DaprDistributedApplicationLifecycleHook.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,17 @@ public async Task BeforeStartAsync(DistributedApplicationModel appModel, Cancell
144144
new EnvironmentCallbackAnnotation(
145145
env =>
146146
{
147+
if (resource is ContainerResource)
148+
{
149+
// By default, the Dapr sidecar will listen on localhost, which is not accessible from the container.
150+
151+
var grpcEndpoint = $"http://localhost:{{{{- portFor \"{daprSideCarResourceName}_grpc\" -}}}}";
152+
var httpEndpoint = $"http://localhost:{{{{- portFor \"{daprSideCarResourceName}_http\" -}}}}";
153+
154+
env.TryAdd("DAPR_GRPC_ENDPOINT", HostNameResolver.ReplaceLocalhostWithContainerHost(grpcEndpoint, _configuration));
155+
env.TryAdd("DAPR_HTTP_ENDPOINT", HostNameResolver.ReplaceLocalhostWithContainerHost(httpEndpoint, _configuration));
156+
}
157+
147158
env.TryAdd("DAPR_GRPC_PORT", $"{{{{- portFor \"{daprSideCarResourceName}_grpc\" -}}}}");
148159
env.TryAdd("DAPR_HTTP_PORT", $"{{{{- portFor \"{daprSideCarResourceName}_http\" -}}}}");
149160
}));

src/Aspire.Hosting/Utils/HostNameResolver.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,18 @@
55

66
namespace Aspire.Hosting.Utils;
77

8-
internal class HostNameResolver
8+
/// <summary>
9+
/// Helpers to resolve host names when running in a containers.
10+
/// </summary>
11+
public class HostNameResolver
912
{
10-
// HACK: When the destination resource is a container, we need to replace the localhost with host.docker.internal
11-
// so the container can access the other container via the host's IP address.
12-
internal static string ReplaceLocalhostWithContainerHost(string value, IConfiguration configuration)
13+
/// <summary>
14+
/// Resolves the "localhost" with the container host name.
15+
/// </summary>
16+
/// <param name="value">The value that contains the localhost</param>
17+
/// <param name="configuration">The configuration object.</param>
18+
/// <returns>A new value with localhost replaced with the container host name</returns>
19+
public static string ReplaceLocalhostWithContainerHost(string value, IConfiguration configuration)
1320
{
1421
// https://stackoverflow.com/a/43541732/45091
1522

0 commit comments

Comments
 (0)