Imagine watching your favorite movies and TV shows anytime, anywhere, without worrying about slow loading times. That's the power of a movie streaming web app like Netflix.
But what if you could build your movie streaming web app without managing the infrastructure? That's where Aptible comes in.
Aptible is a platform that streamlines the code shipping process for development teams, facilitating deployment, monitoring, and infrastructure scaling. This means you can focus on building your app while Aptible takes care of the rest.
This article will show you how to build a movie streaming web app like Netflix using Aptible, from choosing the right technologies to deploying your app to production.
Node.js, MySQL, and Aptible are well-suited technologies for building scalable, performant, and secure streaming web apps.
Aptible makes it easy to deploy your movie streaming web app to production. You can upload your code to Aptible, and it will take care of the rest, including setting up the necessary infrastructure and configuring your app.
Aptible can automatically scale your movie streaming web app up or down based on demand. This is important for movie streaming apps, which can experience spikes in traffic at certain times of the day or during popular movie releases.
Aptible provides built-in monitoring for your movie streaming web app. You can track your app's performance and identify potential problems early on.
Aptible provides a variety of metrics, including CPU usage, memory usage, and response times, which can help you keep your movie streaming web app running smoothly and prevent major outages.
Aptible provides various security features to protect your movie streaming web app from attack. These features include:
Aptible's team’s feature allows you to create groups of users and assign different permissions to each team.
Aptible's environments feature allows you to create multiple isolated environments for your app. This can be useful for testing your app and deploying changes in a controlled manner.
Aptible automatically backs up your app's data regularly. This can help you recover your data in case of a problem, such as a hardware failure or a software bug.
Aptible provides 24/7 support to help you with any problems you may have. You can contact Aptible's support team via email, chat, or phone.
First, you need to create a MySQL database to store movie information. In this tutorial, you will use phpMyAdmin.
Create a new database and a table for movies:
CREATE DATABASE movie_db;
USE movie_db;
CREATE TABLE movies (
id INT AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(255) NOT NULL,
video_url VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
description TEXT,
rating DECIMAL(3, 1),
release_year INT
);
Please create a new Node.js
project folder and initialize it as a Node.js project.
mkdir movie-app
cd movie-app
npm init -y
Install the required dependencies:
npm install express mysql2 multer
express
: A popular Node.js framework for building web applications.mysql2
: A MySQL client for Node.js.multer
: Middleware for handling file uploads.In your Node.js
project, create a db.js
file to set up the MySQL database connection:
// db.js
const mysql = require('mysql2');
const db = mysql.createConnection({
host: 'localhost', // Change to your MySQL host
user: 'root', // Change to your MySQL username
password: 'password', // Change to your MySQL password
database: 'movie_db',
});
db.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
throw err;
}
console.log('Connected to the database');
});
const createTable = `
CREATE TABLE IF NOT EXISTS movies (
id INT AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(255) NOT NULL,
video_url VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
description TEXT,
rating DECIMAL(3, 1),
release_year INT
)
`;
db.query(createTable, (err) => {
if (err) {
console.error("Error creating movies table:", err);
} else {
console.log("Movies table created or already exists");
}
});
module.exports = db;
Replace 'your_username'
and 'your_password'
with your MySQL credentials.
In your Node.js project, create an app.js
file to define your API endpoints using Express:
// app.js
const express = require('express');
const db = require('./db'); // Import the database connection
const multer = require('multer');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Configure Multer for handling file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname);
},
});
const upload = multer({ storage });
// Create a new movie
app.post('/movies', upload.fields([{ name: 'image', maxCount: 1 }, { name: 'video', maxCount: 1 }]), (req, res) => {
const { title, genre, description, rating, release_year } = req.body;
const image_url = req.files['image'][0].path;
const video_url = req.files['video'][0].path;
const query = 'INSERT INTO movies (image_url, video_url, title, genre, description, rating, release_year) VALUES (?, ?, ?, ?, ?, ?, ?)';
const values = [image_url, video_url, title, genre, description, rating, release_year];
db.query(query, values, (err, result) => {
if (err) {
console.error('Error creating a movie:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.status(201).json({ message: 'Movie created successfully' });
}
});
});
// List all movies
app.get('/movies', (req, res) => {
const query = 'SELECT * FROM movies';
db.query(query, (err, rows) => {
if (err) {
console.error('Error listing movies:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.status(200).json(rows);
}
});
});
// Search movies
app.get('/movies/search', (req, res) => {
const { query } = req.query;
const searchQuery = `%${query}%`;
const searchSql = 'SELECT * FROM movies WHERE title LIKE ? OR genre LIKE ?';
const searchValues = [searchQuery, searchQuery];
db.query(searchSql, searchValues, (err, rows) => {
if (err) {
console.error('Error searching movies:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.status(200).json(rows);
}
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Base URL: http://localhost:3000/
/movies
Body:
{
"title": "Movie Title",
"description": "Movie description goes here.",
"release_year": 2023,
"genre": "Action",
"rating": 8.5,
"image_url": "https://example.com/movie-image.jpg",
"video_url": "https://example.com/movie-video.mp4"
}
Status: 201 Created
Body:
jsonCopy code{
"message": "Movie created successfully"
/movies
Status: 200 OK
Body: An array of movie objects. Each object includes the following fields:
jsonCopy code[
{
"id": 1,
"title": "Movie Title 1",
"description": "Movie description goes here.",
"release_year": 2022,
"genre": "Drama",
"rating": 7.9,
"image_url": "https://example.com/movie1-image.jpg",
"video_url": "https://example.com/movie1-video.mp4"
},
{
"id": 2,
"title": "Movie Title 2",
"description": "Another movie description.",
"release_year": 2021,
"genre": "Comedy",
"rating": 6.8,
"image_url": "https://example.com/movie2-image.jpg",
"video_url": "https://example.com/movie2-video.mp4"
}
]
Start your app by running the following command:
node app.js
Once your app runs, you can test the endpoints using an API testing platform.
You can check your phpMyAdmin interface to confirm the data was saved successfully.
Once you have pushed your code to GitHub, you can deploy it to Aptible.
Code folder structure
To see the complete codebase, please check out my GitHub repository at https://github.com/wise4rmgod/moviedb
1: Create environment
Go to the Aptible dashboard and click on the Environments tab.
Click on the Create Environment button.
Enter a name for the environment and select the appropriate region.
Click on the Create Environment button.
2: Create Database
In this tutorial, you will create a MySQL database.
After creating the database, go to the dashboard and click on the reveal to see your connection URL
To avoid this error
ERROR 1045 (28000): Access denied for user 'aptible'@'ip-[IP_ADDRESS].ec2.internal' (using password: YES)
Add this field to your db.js
ssl: { rejectUnauthorized: false, ciphers: "DHE-RSA-AES256-SHA" },
Complete db.js
const mysql = require("mysql2");
const db = mysql.createConnection({
host: "", // Change to your MySQL aptible host
user: "aptible", // Change to your MySQL username
password: "", // Change to your MySQL password
database: "db",
ssl: { rejectUnauthorized: false, ciphers: "DHE-RSA-AES256-SHA" },
port: 26038,
});
db.connect((err) => {
if (err) {
console.error("Error connecting to the database:", err);
throw err;
}
console.log("Connected to the database");
});
const createTable = `
CREATE TABLE IF NOT EXISTS movies (
id INT AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(255) NOT NULL,
video_url VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
description TEXT,
rating DECIMAL(3, 1),
release_year INT
)
`;
db.query(createTable, (err) => {
if (err) {
console.error("Error creating movies table:", err);
} else {
console.log("Movies table created or already exists");
}
});
module.exports = db;
3: Create an App
Then, create an App by giving the Handle a name, and click Save App
Aptible will take some time to provision your app
Once provisioning is complete, click on the app name and click Get Started to continue the deployment process.
4: Upload your SSH public key.
5: Create a Dockerfile
Sample Dockerfile here
# Use the official Node.js image as the base image
FROM node:16
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package*.json ./
# Install project dependencies
RUN npm install
# Copy the application code to the container
COPY . .
# Expose the port that the app will run on
EXPOSE 3000
# Start the application
CMD ["node", "app.js"]
6: Deploy to Aptible via Git remote
The Aptible Git remote URL is specific to your account. You can find it in the Get Started tab of your app's dashboard.
Add the Aptible Git remote for this app, then push to the remote to begin deployment:
git remote add aptible [email protected]:env-prodzz/movieapp.git
Push your code to Aptible.
git push aptible main
If successful, you will see an image similar to the following.
7: Add an Endpoint
Once the endpoint has been created, you can send a GET
, POST
, DELETE
, or any other supported HTTP method to the endpoint using an API testing platform.
To test the endpoint, copy the HOSTNAME from the endpoint's dashboard and use it in your API testing platform.
8: Test your final project
In this article, you learned how to build a movie streaming app like Netflix using Node.js, MySQL, and Aptible. You also learned about the benefits of using these technologies for building streaming web apps and the steps involved in deploying a Node.js app to Aptible.
If you want to build a movie streaming app like Netflix, I recommend using Node.js, MySQL, and Aptible. These technologies are well-suited for building scalable, performant, secure streaming web apps.