-
Notifications
You must be signed in to change notification settings - Fork 147
Add automatic Dockerfile generation with version detection for Golang integration #969
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
fa7b26d
9052215
590c9e0
1e62e49
3acd732
46c54ea
4fb890c
880ac36
65106bf
2ce0835
6897c21
927da41
8c72923
c9ac6c1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,5 +1,11 @@ | ||||||||||||||||||||||||||||||||||
| using Aspire.Hosting.ApplicationModel; | ||||||||||||||||||||||||||||||||||
| using CommunityToolkit.Aspire.Utils; | ||||||||||||||||||||||||||||||||||
| using System.Diagnostics; | ||||||||||||||||||||||||||||||||||
| using System.Globalization; | ||||||||||||||||||||||||||||||||||
| using System.Text.RegularExpressions; | ||||||||||||||||||||||||||||||||||
| using Microsoft.Extensions.Logging; | ||||||||||||||||||||||||||||||||||
| using Microsoft.Extensions.DependencyInjection; | ||||||||||||||||||||||||||||||||||
| using Microsoft.Extensions.Logging.Abstractions; | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| namespace Aspire.Hosting; | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
|
|
@@ -68,10 +74,148 @@ public static IResourceBuilder<GolangAppExecutableResource> AddGolangApp(this ID | |||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| return builder.AddResource(resource) | ||||||||||||||||||||||||||||||||||
| .WithGolangDefaults() | ||||||||||||||||||||||||||||||||||
| .WithArgs([.. allArgs]); | ||||||||||||||||||||||||||||||||||
| .WithArgs([.. allArgs]) | ||||||||||||||||||||||||||||||||||
| .PublishAsGolangDockerfile(workingDirectory, executable, buildTags); | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| private static IResourceBuilder<GolangAppExecutableResource> WithGolangDefaults( | ||||||||||||||||||||||||||||||||||
| this IResourceBuilder<GolangAppExecutableResource> builder) => | ||||||||||||||||||||||||||||||||||
| builder.WithOtlpExporter(); | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| /// <summary> | ||||||||||||||||||||||||||||||||||
| /// Configures the Golang application to be published as a Dockerfile with automatic multi-stage build generation. | ||||||||||||||||||||||||||||||||||
| /// </summary> | ||||||||||||||||||||||||||||||||||
| /// <param name="builder">The resource builder.</param> | ||||||||||||||||||||||||||||||||||
| /// <param name="workingDirectory">The working directory containing the Golang application.</param> | ||||||||||||||||||||||||||||||||||
| /// <param name="executable">The path to the Golang package directory or source file to be executed.</param> | ||||||||||||||||||||||||||||||||||
| /// <param name="buildTags">The optional build tags to be used when building the Golang application.</param> | ||||||||||||||||||||||||||||||||||
| /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> | ||||||||||||||||||||||||||||||||||
| #pragma warning disable ASPIREDOCKERFILEBUILDER001 | ||||||||||||||||||||||||||||||||||
| private static IResourceBuilder<GolangAppExecutableResource> PublishAsGolangDockerfile( | ||||||||||||||||||||||||||||||||||
| this IResourceBuilder<GolangAppExecutableResource> builder, | ||||||||||||||||||||||||||||||||||
| string workingDirectory, | ||||||||||||||||||||||||||||||||||
| string executable, | ||||||||||||||||||||||||||||||||||
| string[]? buildTags) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| const string DefaultAlpineVersion = "3.21"; | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| return builder.PublishAsDockerFile(publish => | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| publish.WithDockerfileBuilder(workingDirectory, context => | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| var buildArgs = new List<string> { "build", "-o", "/app/server" }; | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| if (buildTags is { Length: > 0 }) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| buildArgs.Add("-tags"); | ||||||||||||||||||||||||||||||||||
| buildArgs.Add(string.Join(",", buildTags)); | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| buildArgs.Add(executable); | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| // Get custom base image from annotation, if present | ||||||||||||||||||||||||||||||||||
| context.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation); | ||||||||||||||||||||||||||||||||||
tommasodotNET marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||||||||||||||||||||||
| var goVersion = baseImageAnnotation?.BuildImage ?? GetDefaultGoBaseImage(workingDirectory, context.Services); | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| var buildStage = context.Builder | ||||||||||||||||||||||||||||||||||
| .From(goVersion, "builder") | ||||||||||||||||||||||||||||||||||
| .WorkDir("/build") | ||||||||||||||||||||||||||||||||||
| .Copy(".", "./") | ||||||||||||||||||||||||||||||||||
| .Run(string.Join(" ", ["go", .. buildArgs])); | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| var runtimeImage = baseImageAnnotation?.RuntimeImage ?? $"alpine:{DefaultAlpineVersion}"; | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| context.Builder | ||||||||||||||||||||||||||||||||||
| .From(runtimeImage) | ||||||||||||||||||||||||||||||||||
| .CopyFrom(buildStage.StageName!, "/app/server", "/app/server") | ||||||||||||||||||||||||||||||||||
| .Entrypoint(["/app/server"]); | ||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| #pragma warning restore ASPIREDOCKERFILEBUILDER001 | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| private static string GetDefaultGoBaseImage(string workingDirectory, IServiceProvider serviceProvider) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| const string DefaultGoVersion = "1.23"; | ||||||||||||||||||||||||||||||||||
| var logger = serviceProvider.GetService<ILogger<GolangAppExecutableResource>>() ?? NullLogger<GolangAppExecutableResource>.Instance; | ||||||||||||||||||||||||||||||||||
| var goVersion = DetectGoVersion(workingDirectory, logger) ?? DefaultGoVersion; | ||||||||||||||||||||||||||||||||||
| return $"golang:{goVersion}"; | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| /// <summary> | ||||||||||||||||||||||||||||||||||
| /// Detects the Go version to use for a project by checking go.mod and the installed Go toolchain. | ||||||||||||||||||||||||||||||||||
| /// </summary> | ||||||||||||||||||||||||||||||||||
| /// <param name="workingDirectory">The working directory of the Go project.</param> | ||||||||||||||||||||||||||||||||||
| /// <param name="logger">The logger for diagnostic messages.</param> | ||||||||||||||||||||||||||||||||||
| /// <returns>The detected Go version as a string, or <c>null</c> if no version is detected.</returns> | ||||||||||||||||||||||||||||||||||
| private static string? DetectGoVersion(string workingDirectory, ILogger logger) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| // Check go.mod file | ||||||||||||||||||||||||||||||||||
| var goModPath = Path.Combine(workingDirectory, "go.mod"); | ||||||||||||||||||||||||||||||||||
| if (File.Exists(goModPath)) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| try | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| var goModContent = File.ReadAllText(goModPath); | ||||||||||||||||||||||||||||||||||
| // Look for "go X.Y" or "go X.Y.Z" line in go.mod | ||||||||||||||||||||||||||||||||||
| var match = Regex.Match(goModContent, @"^\s*go\s+(\d+\.\d+(?:\.\d+)?)", RegexOptions.Multiline); | ||||||||||||||||||||||||||||||||||
| if (match.Success) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| var version = match.Groups[1].Value; | ||||||||||||||||||||||||||||||||||
| // Extract major.minor (e.g., "1.22" from "1.22.3") | ||||||||||||||||||||||||||||||||||
| var versionParts = version.Split('.'); | ||||||||||||||||||||||||||||||||||
| if (versionParts.Length >= 2) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| var majorMinor = $"{versionParts[0]}.{versionParts[1]}"; | ||||||||||||||||||||||||||||||||||
| logger.LogDebug("Detected Go version {Version} from go.mod file", majorMinor); | ||||||||||||||||||||||||||||||||||
| return majorMinor; | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| catch (Exception ex) | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| logger.LogDebug(ex, "Failed to parse go.mod file"); | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||
| catch (Exception ex) | |
| { | |
| logger.LogDebug(ex, "Failed to parse go.mod file"); | |
| } | |
| catch (IOException ex) | |
| { | |
| logger.LogDebug(ex, "Failed to parse go.mod file due to IO error"); | |
| } | |
| catch (UnauthorizedAccessException ex) | |
| { | |
| logger.LogDebug(ex, "Failed to parse go.mod file due to unauthorized access"); | |
| } | |
| catch (RegexMatchTimeoutException ex) | |
| { | |
| logger.LogDebug(ex, "Failed to parse go.mod file due to regex timeout"); | |
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed by catching specific exception types: IOException, UnauthorizedAccessException, and RegexMatchTimeoutException. (6897c21)
Outdated
Copilot
AI
Nov 16, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reading the output stream before calling WaitForExit() can cause a deadlock if the process writes enough data to fill the output buffer. The process will block waiting for the buffer to be read, while the code waits for the process to exit. Consider using process.WaitForExit() first, or use asynchronous read operations, or read both StandardOutput and StandardError concurrently.
| var output = process.StandardOutput.ReadToEnd(); | |
| process.WaitForExit(); | |
| // Read both output and error asynchronously, then wait for process exit | |
| var outputTask = process.StandardOutput.ReadToEndAsync(); | |
| var errorTask = process.StandardError.ReadToEndAsync(); | |
| process.WaitForExit(); | |
| var output = outputTask.GetAwaiter().GetResult(); | |
| var error = errorTask.GetAwaiter().GetResult(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed by reading both StandardOutput and StandardError asynchronously before calling WaitForExit() to prevent potential deadlock. (6897c21)
Outdated
Copilot
AI
Nov 16, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Generic catch clause.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed by catching specific exception types: IOException and Win32Exception (for go command not found). (6897c21)
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,6 +29,41 @@ To have the Golang application listen on the correct port, you can use the follo | |
| r.Run(":"+os.Getenv("PORT")) | ||
| ``` | ||
|
|
||
| ## Publishing | ||
|
|
||
| When publishing your Aspire application, the Golang resource automatically generates a multi-stage Dockerfile for containerization. This means you don't need to manually create a Dockerfile for your Golang application. | ||
|
|
||
| ### Automatic Version Detection | ||
|
|
||
| The integration automatically detects the Go version to use by: | ||
| 1. Checking the `go.mod` file for the Go version directive | ||
| 2. Falling back to the installed Go toolchain version | ||
| 3. Using Go 1.23 as the default if no version is detected | ||
|
|
||
| ### Customizing Base Images | ||
|
|
||
| You can customize the base images used in the Dockerfile by using the `DockerfileBaseImageAnnotation`: | ||
|
|
||
| ```csharp | ||
| var golang = builder.AddGolangApp("golang", "../gin-api") | ||
| .WithHttpEndpoint(env: "PORT") | ||
| .WithAnnotation(new DockerfileBaseImageAnnotation | ||
|
||
| { | ||
| BuildImage = "golang:1.22-alpine", // Custom build stage image | ||
| RuntimeImage = "alpine:3.20" // Custom runtime stage image | ||
| }); | ||
| ``` | ||
|
|
||
| ### Generated Dockerfile | ||
|
|
||
| The automatically generated Dockerfile: | ||
| - Uses the detected or default Go version (e.g., `golang:1.22`) as the build stage | ||
| - Uses `alpine:3.21` as the runtime stage for a smaller final image | ||
| - Respects your build tags if specified | ||
| - Builds the executable specified in your `AddGolangApp` call | ||
|
|
||
| This automatic Dockerfile generation happens when you publish your Aspire application and requires no additional configuration. | ||
|
|
||
| ## Additional Information | ||
|
|
||
| https://learn.microsoft.com/dotnet/aspire/community-toolkit/hosting-golang | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.