Deploy a .NET 6 Web app with a Postgres database to Railway
I've really just finished getting everything working, so this is the solution without any revisions. Probably lots of areas for improvements and less than elegant solutions, but hey it works.
- Railway account
- Project is on Github
8. Select the block containing your application and add these variables with the same names and values as in the postgres block. Add an additional variable here with the key PORT and value 3000
- Create a new class named ConnectionHelper. This will check the environment variables that you set inside railway. If those values are null it can be assumed the application is launching locally and will instead use the local connection string.
2.❗IMPORTANT❗ Make sure to change the database value in the local connection string to match the name of your database, optionally change the MYCONNECTIONSTRING to your desired name.
public static class ConnectionHelper
{
public static string getConnectionString()
{
string MYCONNECTIONSTRING = "";
if (Environment.GetEnvironmentVariable("PGHOST") != null)
{
MYCONNECTIONSTRING =
$"Server={Environment.GetEnvironmentVariable("PGHOST")};" +
$"Database={Environment.GetEnvironmentVariable("DATABASE_URL")};" +
$"Port={Environment.GetEnvironmentVariable("PGPORT")};" +
$"Username={Environment.GetEnvironmentVariable("POSTGRES_USER")};" +
$"Password={Environment.GetEnvironmentVariable("PGPASSWORD")}";
}
else
{
MYCONNECTIONSTRING = "Server=localhost;Database=MYDATABASE;Port=5432;Username=postgres;Password=password123";
}
return MYCONNECTIONSTRING;
}
}
- Alter the following line in program.cs to match the following, changing MYDBCONTEXT and MYDBNOTFOUND to match your existing names
builder.Services.AddDbContext<MYDBCONTEXT>(
options =>
options
.UseNpgsql(ConnectionHelper.getConnectionString()
?? throw new InvalidOperationException(
"Connection String 'MYDBNOTFOUND' not found"
)
)
.UseSnakeCaseNamingConvention()
);
- Below the line
var app = builder.Build();
in program.cs Add the following block of code, this is the programmatic version ofupdate-database
and so ensures our remote DB has our migrations. Again changing MYDBCONTEXT to match your existing one.
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<MYDBCONTEXT>();
// This will throw an exception if the connection fails
dbContext.Database.Migrate();
}
- Right click servers, go to register, and finally server...
- Inside this window give the server a name (doesn't matter what it is)
- Head to the connection tab Here we will be using values from the variables tab from Railway
- Host name/address = PGHOST
- PORT = PGPORT
- Username = PGUSER
- Password = PGPASSWORD After this, hit save.
- CSS not showing
Make this adjustment in your program.cs file, on your builder.
var builder = WebApplication.CreateBuilder(new WebApplicationOptions()
{
Args = args,
ContentRootPath = "/app/out",
WebRootPath = "wwwroot",
});