Deploying Go applications to cloud platforms like Railway can be a breeze when everything is set up correctly.
However, if your main.go file isn't in the root directory, Railway cannot build or deploy the application unless it is provided with a custom Nixpacks configuration or build & deploy commands provided in the deployment settings.
In this post, we’ll walk through a real-world scenario and the steps to resolve this quickly!
The Scenario
You have a Go project with the following structure:
my-go-app/
├── cmd/
│ └── server/
│ └── main.go
├── internal/
│ └── /...
├── go.mod
└── go.sum
Step 0: Let's fail fast
When deploying this app to Railway using the following settings:
- Builder: Nixpacks
-
Build Command:
go build cmd/server/main.go
-
Start Command:
go run cmd/server/main.go
The build phase completes successfully, but the deploy phase fails with errors like:
/bin/bash: line 1: go: command not found
The app doesn’t start because Railway is trying to execute the wrong binary or can't find Go in the runtime environment.
Let’s solve this step by step.
Step 1: Understand the Problem
The issue arises because:
- Railway’s Nixpacks builder defaults to expecting the
main.go
file in the root directory. - By default, Railway’s runtime stage may not include Go, making commands like
go run
unavailable after the build phase. - Without proper configuration, the
main
binary isn’t in the right place for execution.
Step 2: Define a Proper Build and Start Command
To handle this structure, explicitly configure the build and start commands:
- Build Command: Compile the app and place the binary in the project root:
go build cmd/server/main.go
- Start Command: Run the compiled binary:
./main
Conclusion
Deploying a Go application to Railway with a non-root main.go
file requires a few adjustments to your build and deployment settings. By explicitly setting the build and start commands, you can successfully deploy your app.
If you encounter any issues, feel free to share your experience or questions in the comments below!
Top comments (0)