How to host a Java Spring + React application for free
Suppose you have a local app running a Java (Spring) backend and a React frontend, and you would like to host it online for free.
In this blog post, I will show you how I did it using Docker and Render. I also had a mongoDB database running on Mongo Atlas.
If you just want to check out the code, you can find it here, in particular this commit. The final app is hosted here.
There are plenty of tools online to host frontend apps for free, but not so many for backend apps, especially since Heroku recently removed their free tier.
I chose Render, but you can also check out fly.io or AWS Amplify.
Docker configuration
Render doesn’t support Java natively, but it can run arbitrary Docker images (but has limited support for containers). So we need to create a Docker image that contains our backend app:
FROM openjdk:17-jdk-alpine
COPY . .
# This was necessary for me
RUN chmod +x gradlew
# Replace with your build command
RUN ./gradlew build
ENTRYPOINT ["java","-jar","build/libs/<YOUR-APP-NAME>-<YOUR-APP-VERSION>.jar"]
You have to replace <YOUR-APP-NAME> and <YOUR-APP-VERSION> with the name and version of your app. You can find the version in your build.gradle file.
For example, for my lixo app and version = ‘0.0.1’, my .jar file was called lixo-0.0.1.
Check that your Docker image works locally by running docker build — tag=my-app-name . and docker run my-app-name.
Render configuration
Now, let’s create a Render blueprint (the Render equivalent of Docker containers)!
At the root of your project, create a render.yaml file:
services:
- type: web
name: my-app-backend
env: docker
plan: free
rootDir: backend # Your root directory for the Java code
- type: web
name: my-app-frontend
env: static
buildCommand: npm run build
staticPublishPath: ./build
rootDir: frontend # Your root directory for the React code
envVars:
- key: REACT_APP_BACKEND_URL # Use this in your app to fetch data from the backend
value: <YOUR-BACKEND-URL>
This will, when pushed to Render, create two web services: one for the backend and one for the frontend.
Bonus: database configuration
Finally, since my backend was connecting to a database hosted online, I had to configure the database connection. You can do this in the application.properties file:
# Spring Boot MongoDB configuration
spring.data.mongodb.uri=<YOUR-MONGODB-URI>
You can find the URI in the MongoDB Atlas dashboard. It should look something like this: mongodb+srv://[YOUR-MONGODB-USER]:[YOUR-MONGODB-PASSWORD]@[URL]/[YOUR-DATABASE-NAME].
If you need to store a password, you can access environment variables by using the ${} syntax (e.g. ${MONGODB_PASSWORD}). Don’t forget to add them to your Render dashboard (and, when running locally, to set them before running your app).
Thanks!
Still reading? You must be pretty good at paying attention!
I would love to hear your feedback on my other projects, so feel free to look at my GitHub ;)
Thanks for reading and happy coding!