Skip to content

Make server port configurable through environment variables - #2

Open
ibhanu wants to merge 2 commits into
mainfrom
ibhanu/issue1
Open

Make server port configurable through environment variables#2
ibhanu wants to merge 2 commits into
mainfrom
ibhanu/issue1

Conversation

@ibhanu

@ibhanu ibhanu commented Mar 18, 2025

Copy link
Copy Markdown
Owner

Issue
The server port number specified in the .env file was not being respected, as the port was hardcoded to 8080 in multiple places. This made it impossible to run multiple instances on different ports or customize the port through configuration.

Fixed #1

Changes
main.go: Read port from environment variable with fallback to 8080

port := os.Getenv("PORT")
if port == "" {
port = "8080" // Default port if not specified
}
Dockerfile: Make port configurable via environment variable

ENV PORT=8080
EXPOSE ${PORT}
docker-compose.yml: Use environment variable for port mapping

ports:

  • "${PORT:-8080}:${PORT:-8080}"
    environment:
  • PORT=${PORT:-8080}
    Testing Instructions
    Without .env file (default behavior):

make run

Server starts on port 8080

With custom port in .env:

echo "PORT=8081" >> .env
make run

Server starts on port 8081

With Docker Compose:

PORT=8082 docker-compose up

Server starts on port 8082

Additional Notes
If no port is specified, falls back to 8080 for backward compatibility
Configuration cascades through all infrastructure (app, Docker, Docker Compose)
Docker configuration uses the same environment variable, ensuring consistency

Summary by CodeRabbit

  • New Features
    • Enhanced dynamic port configuration: The application now leverages an environment variable to determine its running port. The default remains 8080, but it can be easily overridden at runtime for more flexible deployments.

Issue
The server port number specified in the .env file was not being respected, as the port was hardcoded to 8080 in multiple places. This made it impossible to run multiple instances on different ports or customize the port through configuration.

Changes
main.go: Read port from environment variable with fallback to 8080

port := os.Getenv("PORT")
if port == "" {
    port = "8080" // Default port if not specified
}
Dockerfile: Make port configurable via environment variable

ENV PORT=8080
EXPOSE ${PORT}
docker-compose.yml: Use environment variable for port mapping

ports:
  - "${PORT:-8080}:${PORT:-8080}"
environment:
  - PORT=${PORT:-8080}
Testing Instructions
Without .env file (default behavior):

make run
# Server starts on port 8080
With custom port in .env:

echo "PORT=8081" >> .env
make run
# Server starts on port 8081
With Docker Compose:

PORT=8082 docker-compose up
# Server starts on port 8082
Additional Notes
If no port is specified, falls back to 8080 for backward compatibility
Configuration cascades through all infrastructure (app, Docker, Docker Compose)
Docker configuration uses the same environment variable, ensuring consistency
@ibhanu ibhanu assigned ibhanu and abhayrm and unassigned ibhanu Mar 18, 2025
@coderabbitai

coderabbitai Bot commented Mar 18, 2025

Copy link
Copy Markdown

Walkthrough

This pull request updates the application's port configuration across multiple files. The Dockerfile now defines an environment variable (PORT=8080) and uses it for the exposed port. The docker-compose.yml file switches from a static port mapping to a dynamic one using the same environment variable. In the main.go file, the server port is determined at runtime by retrieving the PORT environment variable, with a fallback to "8080" if not set. These adjustments enable flexible, runtime configuration of the application's port.

Changes

Files Change Summary
Dockerfile, docker-compose.yml Added environment variable PORT and updated port configuration to use this variable (dynamic mapping in docker-compose and variable substitution in Dockerfile).
main.go Imported the os package; modified the server startup logic to read the PORT environment variable with a default value of "8080".

Sequence Diagram(s)

sequenceDiagram
    participant DC as Docker Compose
    participant DF as Dockerfile
    participant APP as Application (main.go)

    DC->>DF: Build with env var PORT (default 8080)
    DF->>APP: Set ENV PORT in container
    APP->>APP: Retrieve PORT from environment variables
    APP->>APP: Start server listening on the determined port
Loading

Poem

I'm a bunny in the code field, hopping with delight,
Changing ports dynamically, making everything just right.
ENV and variables lead my joyful playful race,
With each new line, I hop and show my coding grace.
A rabbit's cheer sings in the light of flexible ports tonight!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Docstrings were successfully generated. (🔄 Check again to generate again)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
main.go (1)

13-17: Swagger documentation still references hardcoded port

The Swagger documentation still specifies localhost:8080 as the host, which could be misleading if a different port is used.

Consider updating the Swagger host annotation to reflect the dynamic port configuration:

// @title Web Server API
// @version 1.0
// @description A REST API server written in Go using gin-gonic framework.
-// @host localhost:8080
+// @host localhost:${PORT}
// @BasePath /api/v1

Or better yet, make it a runtime configuration in your Swagger initialization code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a240a5 and 13b4920.

📒 Files selected for processing (3)
  • Dockerfile (1 hunks)
  • docker-compose.yml (1 hunks)
  • main.go (2 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
main.go (1)
internal/infrastructure/server/server.go (1) (1)
  • NewServer (42:112)
🔇 Additional comments (7)
Dockerfile (2)

38-39: Good addition of configurable port environment variable

Setting a default port as an environment variable provides flexibility for configuration. This aligns well with the PR objectives to make the server port configurable.


42-42: Good update to use dynamic port exposure

Changing from a hardcoded port to the environment variable ensures that the exposed port matches the configured one. This allows for dynamic port configuration at container build or runtime.

main.go (3)

4-6: Appropriate import addition

Adding the os package is necessary for environment variable access.


19-22: Good implementation of environment variable-based port configuration

This implementation correctly reads the port from the PORT environment variable with a sensible fallback to "8080" if not specified.


25-25: Proper server start with dynamic port

The server now correctly starts on the dynamically configured port.

docker-compose.yml (2)

9-9: Good implementation of dynamic port mapping

Changing from a static port mapping to a dynamic one that respects the PORT environment variable allows for flexible port configuration. Using the ${PORT:-8080} syntax provides a sensible default while allowing customization.


11-11: Appropriate environment variable injection

Adding the PORT environment variable to the container ensures that the application running inside can access the configured port value. This is consistent with the changes in main.go that read this environment variable.

coderabbitai Bot added a commit that referenced this pull request Mar 18, 2025
Docstrings generation was requested by @ibhanu.

* #2 (comment)

The following files were modified:

* `main.go`
@coderabbitai

coderabbitai Bot commented Mar 18, 2025

Copy link
Copy Markdown

Note

Generated docstrings for this pull request at #3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Updated port number from environment doesn't take any effect on the server

2 participants