How to optimize resource allocation and cloud database services for Express applications
You may have seen our previous quick-start guide on hosting Express on Upsun which details how to set up your Express applications quickly and effectively on the Upsun PaaS. Well, we wanted to take this guide one step further—providing a guide on how you can optimize the performance of your Express applications by leveraging flexible resource allocation and MariaDB cloud-managed database services. Let’s dive right in!
Flexible resource allocation for your Express apps
Upsun projects are container-based with each service/runtime given its very own container, each with its own CPU/RAM and disk resources available. With flexible resource allocation, you can easily scale up or down by simply changing container storage and CPU/RAM per container, per environment, at any time.
During the first push of your production environment, Upsun will use the default size for each of your service/application containers. In general, the following resources should be effective but you can always adapt those values to your application's needs:
- 1 Node.js container instance
- with CPU: 0.5, memory 224MB
- and 0MB of Disk/Storage
Here’s how you can adapt your resources to serve the needs of your Express application:
How to scale your container storage and CPU/RAM
Once you’ve confirmed your choices, Upsun will then take your selections, gather the previously built images from earlier, apply your resource selections to them, and redeploy your full application. For more information, refer to our documentation on how to manage resources on Upsun.
Utilizing MariaDB open-source database
MariaDB is a much-loved open-source database and cloud-managed database services provider designed to enhance database performance, efficiency, and scope. Want to get those benefits for yourself? Here’s how to start using MariaDB with your Express applications on Upsun:
Create a new environment
To update your application, create a new Git branch as usual via your terminal, implement the changes you wish to make, and push the branch to your GitHub repository.
git switch -c add-mariadb && git push -u origin add-mariadb
Add a MariaDB service to your environment
To add a new MariaDB service to your application, you need first to add a new service definition into your .upsun/config.yaml
file, within the services:
top-level key:
# .upsun/config.yaml
services:
mariadb:
type: mariadb:11.0
Then, add a relationship setting in your application matching the service name mariadb
:
# .upsun/config.yaml
applications:
app:
relationships:
mariadb:
Then push your changes to your repository:
git commit -am "Adding MariadDB 11 service" && git push
Use MariaDB in your application
First, you need to import a Node.js module named mysql2
to interact with your local database. Import it using the following command:
npm install mysql2
Then update your index.js
file with the following:
const express = require('express')
const app = express()
const mysql = require("mysql2/promise");
const port = (process.env.PORT || '3000');
function openConnection() {
let database_password = 'express'
if (process.env.MARIADB_PASSWORD !== undefined) {
database_password = process.env.MARIADB_PASSWORD
}
return mysql.createConnection({ host: (process.env.MARIADB_HOST || '127.0.0.1'), port: (process.env.MARIADB_PORT || '3306'), user: (process.env.MARIADB_USERNAME || 'user'), password: database_password, database: (process.env.MARIADB_PATH || 'express') });
}
function createTable(connection) {
return connection.execute(
'CREATE TABLE IF NOT EXISTS upsuninfo (uid INT(10) NOT NULL AUTO_INCREMENT, username VARCHAR(64) NULL DEFAULT NULL, departname VARCHAR(128) NULL DEFAULT NULL, created DATE NULL DEFAULT NULL, PRIMARY KEY (uid) ) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;'
);
}
function insertData(connection) {
return connection.execute(
"INSERT INTO upsuninfo (username, departname, created) VALUES ('upsun', 'Deploy Friday', '2023-09-29')"
);
}
function readData(connection) {
return connection.query("SELECT * FROM upsuninfo");
}
function dropTable(connection) {
return connection.execute("DROP TABLE upsuninfo");
}
// Define the main route.
app.get('/', async function(req, res){
// Connect to MariaDB.
const connection = await openConnection();
await createTable(connection);
await insertData(connection);
const [rows] = await readData(connection);
const droppedResult = await dropTable(connection);
// Make the output.
const outputString = `Hello, World! - A simple Express web framework template for Upsun
MariaDB Tests:
* Connect and add row:
- Row ID (1): ${rows[0].uid}
- Username (upsun): ${rows[0].username}
- Department (Deploy Friday): ${rows[0].departname}
- Created (2024-04-30): ${rows[0].created}
* Delete row:
- Status (0): ${droppedResult[0].warningStatus}`;
res.set('Content-Type', 'text/plain');
res.send(outputString);
});
// Get PORT and start the server
app.listen(port, function() {
console.log(`Listening on port ${port}`)
});
Finally, commit your changes by using the following:
git commit -am "use MariaDB in index.js" && git push
When pushing a new branch to your repository, It will automatically create a new, inactive Upsun preview environment, based on your branch source code and parent environment data (database and/or assets). This new environment is not active by default which means it does not consume resources, so, to finally test it out, you need to activate it, using the following command:
upsun environment:activate
At the end of the activation, your add-mariadb
environment will be deployed and you can access it via the Console by going to the corresponding environment and clicking on its front URL or by using the following CLI command:
upsun environment:url --primary
A little extra, create a local Docker container using MariaDB
To be able to test MariaDB locally, you need to use a local MariaDB database engine. The fastest way to do this is to either open an SSH tunnel to your environment or add a local Docker container. To add a local Docker container, at the root of your project, create a docker-compose.yaml
file with the following:
version: '3.1'
volumes:
data:
services:
db:
image: mariadb:latest
restart: always
environment:
MARIADB_ROOT_PASSWORD: express
MARIADB_PASSWORD: express
MARIADB_USER: user
MARIADB_DATABASE: express
volumes:
- data:/var/lib/mysql
ports:
- "3306:3306"
You can then start the corresponding Docker container:
docker-compose up -d
Then, commit your file for other teammates to be able to use it:
git commit -am "Docker-compose file" && git push
How to run your Express application locally
If you want to test your route locally, you can use the following commands to start the Node.js server on your index.js
file:
node index.js
And then open in your browser the following link: http://localhost:3000/. When you’re satisfied with your changes, merge your feature branch add-mariadb
to the main
branch using the normal Git workflow to do so:
git checkout main
git merge add-mariadb
git push
Your main
environment will then be automatically deployed and you can access it by either using the Console by going to the corresponding environment and clicking on its front URL or by using the following CLI command:
upsun environment:url --primary
And just like that, you’re ready to play with your Express applications now complete with optimized resources and MariaDB magic. Enjoy!
Stay up-to-date on all the latest from us over on our social media and community channels. Catch us over on Dev.to, Reddit, and Discord.