This example will show how nginx can serve multiple different application on single virtual server using location mapping. This example will specifically focus on application powered by react. Although the method will be similar for others apps too.
NOTE: Use
auto-generate-build.sh
for build automation. Creates build with required entrypoint and copies build accordingly. Use this if you want to save time.
Dependencies of the above script
- jq | json processor
For downloading jq utility
Linux
$ apt update
$ apt install jq
MacOs
$ brew install jq
If you are using auto-generate-build.sh
you don't have to create build manually or have to follow the below steps.
Following are the changes which are required to do before creating build.
- Have to add
process.env.PUBLIC_URL
before each route and link to your app. - Introduce new property
entrypoint
at the root of thepackage.json
file and and give path which you want your application to bind with eg. /v1 or /v2 or /alpha etc... - Now create build of your application.
$ npm run build
The full path of the entire application will look as follows - Example
- app.domain.com/v1
- app.domain.com/alpha
- app.domain.com/beta
App directory structure
/www
/v1
/v2
/app
/beta
// 1. Add prefix process.env.PUBLIC_URL before each path and link
const PREFIX = process.env.PUBLIC_URL;
<Router>
<Route
to={`${PREFIX}/home`}
component={Home}
/>
<Route
to={`${PREFIX}/dashboard`}
component={Dashboard}
/>
<Route
to={`${PREFIX}/settings`}
component={Settings}
/>
</Router>
<Link to={`${PREFIX}/home`}> Home </Link>
<Link to={`${PREFIX}/dashboard`}> Dashboard </Link>
<Link to={`${PREFIX}/settings`}> Settings </Link>
// 2. Introduce new property in package.json
{
"entrypoint": "/v1"
...
}
# 3. Create build and copy that build to specified directory after changes listed above
$ npm run build && cp -r build ../www/v1
$ npm run build && cp -r build ../www/v2
$ npm run build && cp -r build ../www/app
$ npm run build && cp -r build ../www/beta
Prerequisites to run the application
- Nodejs
- Docker
- Docker Compose
- Curl utility
- Bash
NOTE: Before running the application you have to create the build manually by hand and place them to the required directory specified in nginx/nginx.conf
or run the bash script by $ ./auto-generate-build.sh
FEATURE AVAILABLE FOR NOW
Start and run application
# run the application
$ docker-compose up -d
# test
$ curl http://localhost/
$ curl http://localhost/v1
$ curl http://localhost/v2
$ curl http://localhost/beta
References: