Skip to content

Deploying a CyTube App

Introduction

CyTube is a self-hosted synchronized media streaming platform that lets you watch videos together with friends, communities, or teams in real-time. Whether you’re watching YouTube videos, Twitch streams, or locally hosted media, everyone in the room sees the same content at the same time with synchronized playback. It’s like having a virtual movie theater where you control what plays and who joins.

What makes CyTube compelling is its focus on synchronized social viewing. You get real-time chat alongside your video player, playlist management where anyone can queue up content, user authentication with granular permissions, and support for multiple media sources including YouTube, Vimeo, Dailymotion, and more. Host watch parties, run community movie nights, or create dedicated channels for specific content—all with the comfort of knowing you control your own platform.

Whether you’re building a community around shared interests, hosting regular watch parties for your team, or creating a private streaming platform for friends, CyTube provides the foundation you need. Deploying CyTube on Klutch.sh gives you a scalable synchronized streaming platform with persistent storage for channels and user data, reliable infrastructure for real-time synchronization, and the flexibility to customize your streaming experience without depending on third-party platforms.

This comprehensive guide walks you through deploying CyTube on Klutch.sh, configuring persistent storage for channels and playlists, setting up authentication and moderation controls, integrating media sources like YouTube and Twitch, and implementing best practices for running a production synchronized streaming platform.

Why Deploy CyTube on Klutch.sh?

  • Automated Docker Detection: Klutch.sh automatically detects your Dockerfile in the repository root and builds your container without manual configuration
  • Synchronized Streaming: Host watch parties and community viewing sessions with real-time video synchronization
  • Persistent Storage: Built-in support for persistent volumes ensures your channels, playlists, and user data survive deployments
  • Secure Infrastructure: Environment variables for admin credentials and API keys are stored securely
  • Production-Ready: Deploy a streaming platform with confidence using containerized infrastructure
  • Real-Time Chat: WebSocket-based chat runs smoothly on Klutch.sh’s infrastructure
  • Media Integration: Connect to YouTube, Twitch, Vimeo, and other platforms with API support

Prerequisites

Before you begin deploying CyTube on Klutch.sh, ensure you have:

  • A Klutch.sh account with dashboard access
  • A GitHub account for repository hosting
  • Docker installed locally for testing (optional but recommended)
  • Basic understanding of video streaming and media platforms
  • Familiarity with web applications and user authentication
  • Knowledge of Docker containers and deployment concepts
  • API keys for media sources (YouTube Data API recommended)
  • A domain name for your CyTube instance (recommended for production use)
  • Understanding of WebSocket-based real-time communication

Understanding CyTube Architecture

Technology Stack

CyTube is built on Node.js with a focus on real-time synchronization and media streaming:

Core Platform:

  • Node.js for server-side application logic and real-time processing
  • Express.js web framework for HTTP routing and middleware
  • Socket.io for WebSocket-based real-time communication
  • jQuery for client-side interactivity
  • MySQL/MariaDB for user accounts and channel data
  • Redis for session management and caching (optional)

Key Components:

  • Media Server: Handles video playback synchronization and playlist management
  • WebSocket Server: Real-time communication for chat, user events, and playback control
  • Channel Manager: Creates and manages streaming rooms with permissions
  • Playlist Engine: Queue management, autoplay, and media source integration
  • Chat System: Real-time messaging with moderation tools and emotes
  • User Authentication: Account system with permissions and role-based access
  • Media Providers: Integrations with YouTube, Twitch, Vimeo, Dailymotion, and more
  • Admin Panel: Server management, user administration, and configuration
  • Moderation Tools: User banning, chat filtering, and permission management
  • Customization System: Custom CSS, JavaScript, and channel branding

Features:

  • Synchronized video playback across all viewers
  • Real-time chat with emotes and formatting
  • Playlist management with queue and history
  • Multiple media source support (YouTube, Twitch, Vimeo, SoundCloud, etc.)
  • User registration and authentication
  • Channel ownership and permissions
  • Moderator tools for user management
  • Custom emotes and channel branding
  • Poll system for community voting
  • Video library for organizing content
  • Channel privacy settings (public/private/unlisted)
  • User profiles and avatars
  • AFK detection and status indicators
  • Mobile-responsive interface
  • Custom CSS and JavaScript per channel
  • MOTD (Message of the Day) for announcements
  • User ranks and permission levels
  • Playback rate control
  • Volume synchronization options

Installation and Setup

Step 1: Create Your Project Directory

Start by creating a new directory for your CyTube deployment project and initialize a Git repository:

Terminal window
mkdir cytube-klutch
cd cytube-klutch
git init

This directory will contain your Dockerfile, configuration files, and initialization scripts for your synchronized streaming platform.

Step 2: Create the Dockerfile

Create a Dockerfile in your project root directory. Klutch.sh will automatically detect this file and use it to build your container. Here’s a production-ready Dockerfile for CyTube:

FROM node:18-alpine
# Set environment variables
ENV CYTUBE_VERSION=3.96.0 \
CYTUBE_HOME=/cytube \
NODE_ENV=production
# Install system dependencies
RUN apk add --no-cache \
git \
python3 \
make \
g++ \
curl \
bash
# Create cytube user
RUN addgroup -g 1000 cytube && \
adduser -D -u 1000 -G cytube cytube
# Create application directory
WORKDIR /cytube
# Clone CyTube repository
RUN git clone --branch v${CYTUBE_VERSION} --depth 1 https://github.com/calzoneman/sync.git . \
&& chown -R cytube:cytube /cytube
# Switch to cytube user
USER cytube
# Install dependencies
RUN npm install --production
# Copy configuration files
COPY --chown=cytube:cytube config.yaml /cytube/config.yaml
# Create necessary directories
RUN mkdir -p /cytube/chanlogs \
/cytube/chandump \
/cytube/google-drive-subtitles
# Expose CyTube ports
EXPOSE 8080
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD curl -f http://localhost:8080/socketconfig/localhost:8080.json || exit 1
# Start CyTube
CMD ["node", "index.js"]

Key Features of This Dockerfile:

  • Based on Node.js 18 Alpine for small image size
  • Installs build dependencies for native modules
  • Creates dedicated cytube user for security
  • Clones CyTube from official GitHub repository
  • Installs Node.js dependencies in production mode
  • Creates directories for logs and channel dumps
  • Exposes port 8080 for web interface
  • Includes health check for monitoring
  • Runs as non-root user

Step 3: Create Configuration File

Create a config.yaml file for CyTube settings:

# CyTube Configuration File
# For full documentation, see: https://github.com/calzoneman/sync/blob/3.0/docs/config.md
# HTTP server configuration
http:
enabled: true
domain: 'http://localhost:8080'
default-port: 8080
root-domain: 'localhost'
root-domain-escape: 'localhost'
alt-domains:
- 'localhost'
minify: true
max-age: '7d'
gzip: true
gzip-threshold: 1024
cookie-secret: 'change-me-to-a-random-string'
session-timeout: 604800000
# HTTPS configuration (disabled, Klutch.sh handles TLS)
https:
enabled: false
# IO (Socket.io) configuration
io:
domain: 'http://localhost:8080'
default-port: 8080
ip-connection-count: 10
# Database configuration (MySQL/MariaDB)
mysql:
server: 'localhost'
port: 3306
database: 'cytube'
user: 'cytube'
password: 'change-me'
pool-size: 10
# Channel management
channel-storage:
type: 'file'
channel-path: './chandump'
channel-save-interval: 300000
max-channels-per-user: 5
max-accounts-per-ip: 5
# User registration
enable-guest-login: true
# Reserved usernames (cannot be registered)
reserved-names:
usernames:
- 'admin'
- 'administrator'
- 'moderator'
# YouTube API configuration
youtube-v3-key: ''
youtube-v3-max-results: 25
# Google Drive API configuration
google-drive-clientid: ''
google-drive-clientsecret: ''
# Twitch API configuration
twitch-clientid: ''
twitch-clientsecret: ''
# Vimeo API configuration
vimeo-clientid: ''
vimeo-clientsecret: ''
# Playlist limits
playlist:
max-items: 4000
max-duration: 0
# FFMPEG for video processing (optional)
ffmpeg:
enabled: false
# Trust proxied IP addresses (for Klutch.sh)
trust-proxies:
- 'loopback'
- 'uniquelocal'
# Contact and support
contacts:
- name: 'Admin'
title: 'Administrator'
email: 'admin@example.com'
# Stats tracking
stats:
interval: 3600000
max-age: 86400000
# Logging
log:
level: 'info'
# Syslog (disabled)
syslog:
enabled: false
# Service integration toggles
service-socket:
enabled: false
# Allow iframing the site
allow-iframes: false
# CORS headers
cors:
enabled: false
# XSS protection
csp:
enabled: true
# Rate limiting
rate-limit:
window: 60000
max: 100
# Socket.io options
socket-io:
transports:
- 'websocket'
- 'polling'

Step 4: Create Database Initialization Script

Create a init-db.sql file for database setup:

-- CyTube Database Initialization
CREATE DATABASE IF NOT EXISTS cytube CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE cytube;
-- Users table
CREATE TABLE IF NOT EXISTS users (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
password VARCHAR(60) NOT NULL,
global_rank INT NOT NULL,
email VARCHAR(255) NOT NULL,
profile TEXT,
ip VARCHAR(39) NOT NULL,
time BIGINT NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Channels table
CREATE TABLE IF NOT EXISTS channels (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
owner VARCHAR(20) NOT NULL,
time BIGINT NOT NULL,
last_loaded BIGINT NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Channel ranks table
CREATE TABLE IF NOT EXISTS channel_ranks (
id INT NOT NULL AUTO_INCREMENT,
channel_id INT NOT NULL,
user_id INT NOT NULL,
rank INT NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY channel_user (channel_id, user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Channel bans table
CREATE TABLE IF NOT EXISTS channel_bans (
id INT NOT NULL AUTO_INCREMENT,
channel_id INT NOT NULL,
ip VARCHAR(39) NOT NULL,
name VARCHAR(20) NOT NULL,
reason VARCHAR(255),
bannedby VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Libraries table (for saved videos)
CREATE TABLE IF NOT EXISTS channel_libraries (
id INT NOT NULL AUTO_INCREMENT,
channel_id INT NOT NULL,
title VARCHAR(255) NOT NULL,
seconds INT NOT NULL,
type VARCHAR(10) NOT NULL,
id_text VARCHAR(255) NOT NULL,
PRIMARY KEY (id),
KEY channel_id (channel_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Global bans table
CREATE TABLE IF NOT EXISTS global_bans (
ip VARCHAR(39) NOT NULL,
reason VARCHAR(255),
PRIMARY KEY (ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Password resets table
CREATE TABLE IF NOT EXISTS password_reset (
ip VARCHAR(39) NOT NULL,
email VARCHAR(255) NOT NULL,
hash VARCHAR(64) NOT NULL,
expire BIGINT NOT NULL,
PRIMARY KEY (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- User playlists table
CREATE TABLE IF NOT EXISTS user_playlists (
user VARCHAR(20) NOT NULL,
name VARCHAR(255) NOT NULL,
contents MEDIUMTEXT NOT NULL,
count INT NOT NULL,
duration INT NOT NULL,
PRIMARY KEY (user, name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Aliases table (for name history)
CREATE TABLE IF NOT EXISTS aliases (
visit_id INT NOT NULL AUTO_INCREMENT,
ip VARCHAR(39) NOT NULL,
name VARCHAR(20) NOT NULL,
time BIGINT NOT NULL,
PRIMARY KEY (visit_id),
KEY ip (ip),
KEY name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Meta table (for schema version tracking)
CREATE TABLE IF NOT EXISTS meta (
key VARCHAR(255) NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO meta (key, value) VALUES ('schema_version', '8');

Step 5: Create Environment Configuration Script

Create an entrypoint.sh script for environment-based configuration:

#!/bin/bash
# entrypoint.sh - Configure CyTube from environment variables
set -e
CONFIG_FILE="/cytube/config.yaml"
# Update configuration from environment variables
if [ ! -z "$CYTUBE_DOMAIN" ]; then
sed -i "s|domain: 'http://localhost:8080'|domain: '$CYTUBE_DOMAIN'|g" $CONFIG_FILE
sed -i "s|root-domain: 'localhost'|root-domain: '$(echo $CYTUBE_DOMAIN | sed 's|https\?://||')'|g" $CONFIG_FILE
fi
if [ ! -z "$CYTUBE_PORT" ]; then
sed -i "s|default-port: 8080|default-port: $CYTUBE_PORT|g" $CONFIG_FILE
fi
if [ ! -z "$CYTUBE_COOKIE_SECRET" ]; then
sed -i "s|cookie-secret: 'change-me-to-a-random-string'|cookie-secret: '$CYTUBE_COOKIE_SECRET'|g" $CONFIG_FILE
fi
# Database configuration
if [ ! -z "$MYSQL_HOST" ]; then
sed -i "s|server: 'localhost'|server: '$MYSQL_HOST'|g" $CONFIG_FILE
fi
if [ ! -z "$MYSQL_PORT" ]; then
sed -i "s|port: 3306|port: $MYSQL_PORT|g" $CONFIG_FILE
fi
if [ ! -z "$MYSQL_DATABASE" ]; then
sed -i "s|database: 'cytube'|database: '$MYSQL_DATABASE'|g" $CONFIG_FILE
fi
if [ ! -z "$MYSQL_USER" ]; then
sed -i "s|user: 'cytube'|user: '$MYSQL_USER'|g" $CONFIG_FILE
fi
if [ ! -z "$MYSQL_PASSWORD" ]; then
sed -i "s|password: 'change-me'|password: '$MYSQL_PASSWORD'|g" $CONFIG_FILE
fi
# API keys
if [ ! -z "$YOUTUBE_API_KEY" ]; then
sed -i "s|youtube-v3-key: ''|youtube-v3-key: '$YOUTUBE_API_KEY'|g" $CONFIG_FILE
fi
if [ ! -z "$TWITCH_CLIENT_ID" ]; then
sed -i "s|twitch-clientid: ''|twitch-clientid: '$TWITCH_CLIENT_ID'|g" $CONFIG_FILE
fi
if [ ! -z "$TWITCH_CLIENT_SECRET" ]; then
sed -i "s|twitch-clientsecret: ''|twitch-clientsecret: '$TWITCH_CLIENT_SECRET'|g" $CONFIG_FILE
fi
echo "CyTube configuration updated from environment variables"
# Start CyTube
exec node index.js

Step 6: Create Docker Compose for Local Testing

Create a docker-compose.yml file for local development (not used on Klutch.sh):

version: '3.8'
services:
cytube:
build: .
ports:
- "8080:8080"
environment:
- CYTUBE_DOMAIN=http://localhost:8080
- CYTUBE_PORT=8080
- CYTUBE_COOKIE_SECRET=your-random-secret-here
- MYSQL_HOST=mysql
- MYSQL_PORT=3306
- MYSQL_DATABASE=cytube
- MYSQL_USER=cytube
- MYSQL_PASSWORD=cytube_password
- YOUTUBE_API_KEY=your-youtube-api-key
volumes:
- cytube-chanlogs:/cytube/chanlogs
- cytube-chandump:/cytube/chandump
depends_on:
- mysql
mysql:
image: mariadb:10.11
environment:
- MYSQL_ROOT_PASSWORD=root_password
- MYSQL_DATABASE=cytube
- MYSQL_USER=cytube
- MYSQL_PASSWORD=cytube_password
volumes:
- mysql-data:/var/lib/mysql
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
ports:
- "3306:3306"
volumes:
cytube-chanlogs:
cytube-chandump:
mysql-data:

Step 7: Test Locally with Docker Compose (Optional)

Before deploying to Klutch.sh, you can test your CyTube setup locally:

Terminal window
# Make entrypoint script executable
chmod +x entrypoint.sh
# Start the services
docker-compose up -d
# Check logs
docker-compose logs -f cytube
# Access CyTube at http://localhost:8080

When you’re done testing:

Terminal window
# Stop and remove containers
docker-compose down
# Remove volumes (if you want to start fresh)
docker-compose down -v

Step 8: Prepare Your Repository for Deployment

Commit your configuration files to your GitHub repository:

Terminal window
git add Dockerfile config.yaml init-db.sql entrypoint.sh docker-compose.yml
git commit -m "Add CyTube Docker configuration"
git remote add origin https://github.com/yourusername/cytube-klutch.git
git branch -M main
git push -u origin main

Environment Variables Configuration

CyTube requires several environment variables for proper configuration. These should be configured in the Klutch.sh dashboard under your app’s environment variables section.

Essential Environment Variables

Server Configuration:

CYTUBE_DOMAIN=https://example-app.klutch.sh
CYTUBE_PORT=8080
CYTUBE_COOKIE_SECRET=generate-a-random-32-character-string-here

Database Configuration:

MYSQL_HOST=your-mysql-host.klutch.sh
MYSQL_PORT=3306
MYSQL_DATABASE=cytube
MYSQL_USER=cytube
MYSQL_PASSWORD=your-secure-password-here

YouTube API:

YOUTUBE_API_KEY=your-youtube-data-api-v3-key

Optional Environment Variables

Twitch Integration:

TWITCH_CLIENT_ID=your-twitch-client-id
TWITCH_CLIENT_SECRET=your-twitch-client-secret

Vimeo Integration:

VIMEO_CLIENT_ID=your-vimeo-client-id
VIMEO_CLIENT_SECRET=your-vimeo-client-secret

Google Drive Integration:

GOOGLE_DRIVE_CLIENT_ID=your-google-drive-client-id
GOOGLE_DRIVE_CLIENT_SECRET=your-google-drive-client-secret

Session Configuration:

SESSION_TIMEOUT=604800000

Logging:

LOG_LEVEL=info

Obtaining API Keys

YouTube Data API v3:

  1. Go to Google Cloud Console
  2. Create a new project or select an existing one
  3. Enable “YouTube Data API v3”
  4. Create credentials → API key
  5. Copy the API key and add to YOUTUBE_API_KEY

Twitch API:

  1. Go to Twitch Developer Console
  2. Register a new application
  3. Set OAuth Redirect URL to your domain
  4. Copy Client ID and Client Secret

Important Security Notes:

  • Never commit API keys or passwords to your Git repository
  • Use Klutch.sh’s environment variable management for all secrets
  • Generate a strong random string for CYTUBE_COOKIE_SECRET
  • Use strong passwords for MySQL database access
  • Regularly rotate API keys and credentials
  • Enable HTTPS for production deployments (Klutch.sh provides this)

Persistent Storage Configuration

CyTube stores channel data, playlists, chat logs, and user information that must persist across container restarts and deployments. You need to configure persistent volumes for critical directories.

Critical Directories for Persistence

  1. Channel Dumps (/cytube/chandump) - Channel configurations and playlists
  2. Channel Logs (/cytube/chanlogs) - Chat history and channel activity logs
  3. Google Drive Subtitles (/cytube/google-drive-subtitles) - Cached subtitle files (optional)

When creating your CyTube app on Klutch.sh, attach persistent volumes with the following mount paths:

Channel Data Volume:

  • Mount Path: /cytube/chandump
  • Size: 5GB minimum (grows with number of channels and playlists)
  • Purpose: Store channel configurations, playlists, and settings

Chat Logs Volume:

  • Mount Path: /cytube/chanlogs
  • Size: 10GB minimum (grows with chat activity)
  • Purpose: Store chat history for all channels

Subtitles Cache Volume (Optional):

  • Mount Path: /cytube/google-drive-subtitles
  • Size: 1GB (for Google Drive subtitle caching)
  • Purpose: Cache subtitle files for Google Drive videos

Volume Size Recommendations

  • Small Community (1-5 channels, <100 users): 5GB chandump, 10GB chanlogs
  • Medium Community (5-20 channels, 100-500 users): 10GB chandump, 25GB chanlogs
  • Large Community (20-50 channels, 500-2000 users): 20GB chandump, 50GB chanlogs
  • Enterprise (50+ channels, 2000+ users): 50GB+ chandump, 100GB+ chanlogs

Storage requirements vary based on chat activity, number of channels, and playlist sizes. Monitor usage and expand as needed.

Database Storage

CyTube requires a MySQL/MariaDB database. You have two options:

Option 1: Deploy MySQL on Klutch.sh

Deploy a separate MySQL container with persistent storage:

  • Create a new app with official MariaDB image
  • Attach persistent volume to /var/lib/mysql
  • Configure with environment variables
  • Use the Klutch.sh internal URL for MYSQL_HOST

Option 2: Use External Database

Use a managed MySQL service:


Deploying to Klutch.sh

Now that your CyTube project is ready and pushed to GitHub, follow these steps to deploy it on Klutch.sh with persistent storage and proper configuration.

Deployment Steps

    1. Deploy MySQL Database First

      Before deploying CyTube, set up a MySQL/MariaDB database:

      • Create a new app in your Klutch.sh project
      • Name it “cytube-mysql”
      • Use Docker image: mariadb:10.11
      • Set environment variables:
        • MYSQL_ROOT_PASSWORD: Strong root password
        • MYSQL_DATABASE: cytube
        • MYSQL_USER: cytube
        • MYSQL_PASSWORD: Secure password for CyTube
      • Attach persistent volume:
        • Mount Path: /var/lib/mysql
        • Size: 20GB (adjust based on expected usage)
      • Select TCP traffic type
      • Deploy and wait for it to become healthy
    2. Log in to Klutch.sh

      Navigate to klutch.sh/app and sign in to your account.

    3. Create a New Project

      From your dashboard, create a new project. Give it a meaningful name like “Synchronized Streaming” to organize your deployments.

    4. Create a New App for CyTube

      Within your project, create a new app for your CyTube instance.

    5. Select Your Repository

      • Choose GitHub as your Git source
      • Select the repository containing your CyTube Dockerfile
      • Choose the branch you want to deploy (typically main or master)
    6. Configure Traffic Type

      • Traffic Type: Select HTTP (CyTube serves a web interface)
      • Internal Port: Set to 8080 (CyTube’s default HTTP port)
    7. Set Environment Variables

      In the environment variables section, add all the CyTube configuration variables listed in the “Environment Variables Configuration” section above. Ensure sensitive values are marked as secrets.

      Critical Variables (minimum required):

      • CYTUBE_DOMAIN - Set to https://example-app.klutch.sh
      • CYTUBE_PORT - Set to 8080
      • CYTUBE_COOKIE_SECRET - Generate a random 32-character string
      • MYSQL_HOST - Your MySQL container URL or external database host
      • MYSQL_PORT - 3306
      • MYSQL_DATABASE - cytube
      • MYSQL_USER - cytube
      • MYSQL_PASSWORD - Your MySQL password
      • YOUTUBE_API_KEY - Your YouTube Data API key
    8. Attach Persistent Volumes

      This is critical for preserving your channels and chat logs. Add volumes for:

      Channel Data Volume:

      • Mount Path: /cytube/chandump
      • Size: 5GB (or larger based on your needs)

      Chat Logs Volume:

      • Mount Path: /cytube/chanlogs
      • Size: 10GB (or larger for active communities)
    9. Configure Compute Resources

      Select appropriate compute resources based on your usage:

      • Small Community: 1 CPU, 2GB RAM (for 10-50 concurrent users)
      • Medium Community: 2 CPU, 4GB RAM (for 50-200 concurrent users)
      • Large Community: 4 CPU, 8GB RAM (for 200-500 concurrent users)
      • Enterprise: 8+ CPU, 16GB+ RAM (for 500+ concurrent users)
    10. Deploy Your Application

      Click “Create” to start the deployment. Klutch.sh will:

      • Automatically detect your Dockerfile in the repository root
      • Build the Docker image with your configuration
      • Attach the persistent volumes you specified
      • Deploy the container with your environment variables
      • Assign a URL for accessing your CyTube instance
    11. Initialize the Database

      After deployment, you need to initialize the database with the schema:

      • Access your MySQL container via terminal
      • Run the init-db.sql script to create tables
      • Or use a MySQL client to connect and run the initialization script
    12. Access Your CyTube Instance

      Once deployment is complete, you’ll receive a URL like example-app.klutch.sh. Navigate to this URL in your browser to access your CyTube interface.

    13. Create Admin Account

      On first access:

      • Register a new account through the interface
      • Access the MySQL database and manually set global_rank to 255 for admin privileges
      • Or use the CyTube CLI tools to promote your account

Getting Started with CyTube

After deployment, follow these steps to start using your synchronized streaming platform.

Initial Setup and Configuration

  1. Access Your CyTube Instance

    Navigate to your Klutch.sh app URL (e.g., https://example-app.klutch.sh) to access CyTube.

  2. Register an Account

    • Click “Login” in the top-right corner
    • Click “Register” to create a new account
    • Choose a username and secure password
    • Complete the registration
  3. Promote to Administrator

    Connect to your MySQL database and run:

    USE cytube;
    UPDATE users SET global_rank = 255 WHERE name = 'your-username';

    Global ranks in CyTube:

    • 0: Guest
    • 1: Registered user
    • 2: Moderator
    • 3: Administrator
    • 255: Site administrator
  4. Create Your First Channel

    • Click “Channels” in the top menu
    • Click “Register a new channel”
    • Enter a channel name (alphanumeric, no spaces)
    • Set channel options:
      • Public: Visible in channel list
      • Unlisted: Accessible via direct link only
      • Private: Requires password to join
    • Click “Register”

Adding Videos to Playlist

Add YouTube Video:

  1. Click the “Add Video” button in the playlist section
  2. Select “YouTube” as the source
  3. Enter the YouTube video URL or ID
  4. Click “Add” to queue the video

Example YouTube URL:

https://www.youtube.com/watch?v=dQw4w9WgXcQ

Add Multiple Videos:

You can queue multiple videos at once:

  1. Click “Add Video”
  2. Select “YouTube Playlist” or “Custom Embed”
  3. Paste playlist URL or multiple video URLs
  4. CyTube will add all videos to the queue

Supported Media Sources:

  • YouTube (videos and playlists)
  • Twitch (live streams and VODs)
  • Vimeo (videos)
  • Dailymotion (videos)
  • SoundCloud (audio)
  • Google Drive (direct files)
  • Direct video URLs (mp4, webm)
  • Custom embeds (iframe)

Managing Your Channel

Channel Settings:

  1. Click “Channel Settings” (gear icon)
  2. Configure options:
    • General: Channel description, MOTD
    • Permissions: Who can add videos, control playback
    • Moderation: Ban users, manage filters
    • Appearance: Custom CSS and JavaScript
    • Admin: Channel administrators

Permission Ranks:

0 - Guest (anonymous users)
1 - Registered users
2 - Regular (trusted users)
3 - Moderator
4 - Channel Administrator
5 - Channel Owner

Setting Permissions:

// Example: Allow users with rank 1+ to add videos
// In Channel Settings → Permissions:
Add Videos: Rank 1
Delete Videos: Rank 3
Control Playback: Rank 2

Chat Commands

User Commands:

/me [message] - Send an action message
/sp [message] - Send a message visible only to you
/afk - Mark yourself as away from keyboard
/clear - Clear your local chat history
/poll [title]:[option1],[option2],[option3] - Create a poll

Moderator Commands:

/kick [username] - Kick a user from the channel
/ban [username] - Ban a user from the channel
/ipban [username] - Ban a user's IP address
/mute [username] - Mute a user
/smute [username] - Shadow mute (user can see their messages, others can't)
/unmute [username] - Unmute a user
/clean [username] - Remove all messages from a user

Admin Commands:

/rank [username] [rank] - Set user's rank
/promote [username] - Increase user's rank by 1
/demote [username] - Decrease user's rank by 1

Custom Emotes

Add custom emotes to your channel:

  1. Go to Channel Settings → Emotes
  2. Click “Add Emote”
  3. Enter emote name (e.g., danceparrot)
  4. Enter emote image URL
  5. Click “Save”

Use emotes in chat by typing the name:

I love this song! danceparrot

Playlist Management

Creating a Library:

Save videos to your channel library for quick access:

  1. Hover over a video in the playlist
  2. Click “Add to Library”
  3. The video is saved for future use

Loading from Library:

  1. Click “Library” tab
  2. Search for saved videos
  3. Click to add to current playlist

Playlist Operations:

Shuffle: Randomize playlist order
Clear: Remove all videos
Lock Playlist: Prevent changes (moderator only)
Hide Playlist: Collapse playlist view

Synchronization Features

Playback Control:

  • Play/Pause: Everyone sees synchronized playback
  • Skip: Jump to next video (permission-based)
  • Leader: Designated user controls playback for all

Leader Mode:

Enable leader mode for specific users:

  1. User becomes the “leader”
  2. Their playback controls (pause, seek) affect everyone
  3. Perfect for presentations or guided viewing

Timestamp Synchronization:

CyTube continuously synchronizes video timestamps:

// Sync occurs every few seconds
// If you're out of sync, click "Resync" button
// Or refresh the page to force resync

Creating Watch Parties

Schedule a Watch Party:

  1. Create an event announcement in MOTD:

    Movie Night - Friday 8 PM EST
    We're watching: The Matrix
  2. Queue videos in advance:

    • Add movies/shows to playlist
    • Lock playlist to prevent changes
    • Set starting time
  3. Promote in your community:

    • Share channel link
    • Announce in Discord, forums, social media

Watch Party Best Practices:

  • Test videos beforehand to ensure they work
  • Have backup videos ready
  • Assign moderators to help manage chat
  • Use polls to vote on next content
  • Enable slowmode during peak activity

User Profiles and Avatars

Setting Profile Text:

  1. Click your username
  2. Go to “Settings”
  3. Add profile text/bio
  4. Save changes

Custom CSS for Personal Style:

Users with appropriate rank can customize their chat appearance:

/* Custom username color */
.username[data-name="YourName"] {
color: #ff6b6b !important;
font-weight: bold;
}

API and Integration

Embedding CyTube:

You can embed CyTube channels in other websites:

<iframe
src="https://example-app.klutch.sh/r/yourchannel"
width="100%"
height="600"
frameborder="0"
allowfullscreen>
</iframe>

Webhook Integration:

Configure webhooks for channel events:

// Example: Discord webhook for new videos
// Configure in Channel Settings → Admin → Webhooks
{
"event": "video_added",
"channel": "yourchannel",
"video": {
"title": "Amazing Video",
"duration": 240,
"type": "youtube",
"id": "dQw4w9WgXcQ"
},
"user": "username"
}

Bot Development:

Create bots using the CyTube API:

const io = require('socket.io-client');
const socket = io('https://example-app.klutch.sh:8080');
socket.on('connect', () => {
console.log('Connected to CyTube');
// Join a channel
socket.emit('joinChannel', {
name: 'yourchannel'
});
});
socket.on('chatMsg', (data) => {
console.log(`${data.username}: ${data.msg}`);
// Respond to commands
if (data.msg === '!help') {
socket.emit('chatMsg', {
msg: 'Available commands: !help, !uptime, !current'
});
}
});

Production Best Practices

Security Recommendations

Account Security:

  • Enforce strong passwords for all users
  • Limit global administrator accounts
  • Regularly review user ranks and permissions
  • Monitor for suspicious account activity
  • Enable IP-based rate limiting

Channel Security:

  • Set appropriate permission levels for channels
  • Use unlisted or private channels for sensitive content
  • Regularly review channel moderators
  • Implement chat filters for spam prevention
  • Monitor for abusive users and content

Database Security:

  • Use strong MySQL passwords
  • Restrict database access to CyTube container only
  • Regular database backups
  • Enable MySQL SSL connections for external databases
  • Audit database access logs

API Key Security:

  • Rotate API keys periodically
  • Use separate API keys per environment
  • Monitor API quota usage
  • Revoke unused API keys
  • Never expose keys in client-side code

Performance Optimization

Server Configuration:

Optimize CyTube for better performance:

# config.yaml optimizations
# Increase connection limits for large audiences
io:
ip-connection-count: 20
# Enable caching
http:
max-age: '30d'
gzip: true
gzip-threshold: 512
# Database connection pooling
mysql:
pool-size: 20
# Reduce channel save frequency for high activity
channel-save-interval: 600000

Resource Allocation:

  • Allocate sufficient memory for WebSocket connections
  • Monitor CPU usage during peak hours
  • Use SSD storage for database and logs
  • Consider Redis for session caching
  • Monitor network bandwidth for streaming

Client-Side Performance:

  • Enable minification in config
  • Use CDN for static assets
  • Limit playlist size to reasonable numbers
  • Optimize custom CSS and JavaScript
  • Compress images used in emotes

Database Optimization:

-- Add indexes for better query performance
CREATE INDEX idx_channel_name ON channels(name);
CREATE INDEX idx_user_name ON users(name);
CREATE INDEX idx_channel_ranks_lookup ON channel_ranks(channel_id, user_id);
-- Regular maintenance
OPTIMIZE TABLE users;
OPTIMIZE TABLE channels;
OPTIMIZE TABLE channel_libraries;

Monitoring and Maintenance

Health Monitoring:

  • Check application health endpoint regularly
  • Monitor WebSocket connection counts
  • Track video playback errors
  • Review chat activity metrics
  • Monitor disk usage for logs and dumps

Logging Best Practices:

# config.yaml logging configuration
log:
level: 'info' # Use 'debug' for troubleshooting
# Log rotation strategy
# Keep logs for 30 days, then archive

Regular Maintenance Tasks:

  • Daily: Review error logs
  • Daily: Check disk space usage
  • Weekly: Review new user registrations
  • Weekly: Check for CyTube updates
  • Monthly: Audit user ranks and permissions
  • Monthly: Review and prune old channels
  • Quarterly: Database optimization and cleanup
  • Quarterly: Security audit and updates

Backup Strategy:

# Automated backup script
#!/bin/bash
BACKUP_DIR="/backups/cytube"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# Backup channel data
tar -czf "${BACKUP_DIR}/chandump-${TIMESTAMP}.tar.gz" /cytube/chandump
# Backup database
mysqldump -h $MYSQL_HOST -u $MYSQL_USER -p$MYSQL_PASSWORD cytube | \
gzip > "${BACKUP_DIR}/database-${TIMESTAMP}.sql.gz"
# Backup chat logs (optional, can be large)
tar -czf "${BACKUP_DIR}/chanlogs-${TIMESTAMP}.tar.gz" /cytube/chanlogs
# Keep backups for 30 days
find "${BACKUP_DIR}" -name "*.tar.gz" -mtime +30 -delete
find "${BACKUP_DIR}" -name "*.sql.gz" -mtime +30 -delete

Scaling Considerations

Horizontal Scaling:

CyTube can be scaled horizontally with proper configuration:

  1. Use external MySQL database (not on same container)
  2. Implement Redis for session sharing
  3. Deploy multiple CyTube instances
  4. Use load balancer for traffic distribution
  5. Configure sticky sessions for WebSocket

Vertical Scaling:

For single-instance deployments:

  • Monitor concurrent user metrics
  • Scale CPU/RAM based on load
  • Optimize database queries
  • Use caching strategically

Traffic Projections:

Resource requirements per concurrent users:
- 100 users: 1 CPU, 2GB RAM
- 500 users: 2 CPU, 4GB RAM
- 1000 users: 4 CPU, 8GB RAM
- 2000+ users: 8+ CPU, 16GB+ RAM
Network bandwidth per 100 concurrent users:
- ~10 Mbps (chat and synchronization)
- Video bandwidth handled by source (YouTube, etc.)

Content Moderation

Automated Filters:

Configure chat filters in channel settings:

// Example chat filter regex patterns
blocked_words: [
/spam-pattern/gi,
/advertisement/gi,
/inappropriate-content/gi
]
// URL filtering
allow_external_links: false // Moderators only

Moderation Tools:

  • Real-time chat monitoring
  • User ban/mute system
  • IP-based restrictions
  • Shadow mute for problematic users
  • Chat history for evidence

Community Guidelines:

Create and enforce community guidelines:

  1. Post rules in channel MOTD
  2. Train moderators on policies
  3. Document common scenarios
  4. Regular moderator meetings
  5. User reporting system

Troubleshooting

Common Issues and Solutions

Issue: Cannot Access CyTube Web Interface

  • Check: Verify container is running in Klutch.sh dashboard
  • Check: Confirm internal port 8080 is correctly configured
  • Check: Ensure HTTP traffic type is selected
  • Check: Review container logs for startup errors
  • Solution: Restart deployment if configuration changed
  • Solution: Verify CYTUBE_DOMAIN matches your actual domain

Issue: Videos Not Playing

  • Check: Verify YouTube API key is valid and has quota remaining
  • Check: Confirm video is not region-restricted or private
  • Check: Test different media sources (Vimeo, direct links)
  • Check: Review browser console for errors
  • Solution: Check API key quota in Google Cloud Console
  • Solution: Try alternative video sources
  • Solution: Update media provider configurations

Issue: Chat Messages Not Appearing

  • Cause: WebSocket connection issues
  • Check: Verify WebSocket connection in browser console
  • Check: Confirm firewall rules allow WebSocket traffic
  • Solution: Check browser WebSocket support
  • Solution: Try different browser
  • Solution: Verify io.domain configuration matches deployment

Issue: Database Connection Errors

  • Check: Verify MySQL container is running and healthy
  • Check: Confirm database credentials in environment variables
  • Check: Test database connectivity from CyTube container
  • Solution: Verify MYSQL_HOST points to correct database
  • Solution: Check MySQL user permissions
  • Solution: Initialize database with init-db.sql script

Issue: Playback Out of Sync

  • Cause: Network latency or browser performance issues
  • Check: Monitor network connection quality
  • Check: Review server load and resource usage
  • Solution: Click “Resync” button in player controls
  • Solution: Refresh browser page
  • Solution: Reduce other bandwidth-heavy activities

Issue: Persistent Data Lost After Redeployment

  • Cause: Persistent volumes not properly attached
  • Check: Verify volume mount paths match exactly: /cytube/chandump, /cytube/chanlogs
  • Check: Confirm volumes have sufficient available space
  • Solution: Re-attach volumes with correct mount paths before deploying
  • Solution: Restore from backups if data was lost

Issue: High Memory Usage

  • Cause: Large number of concurrent users or memory leak
  • Check: Monitor active user count and channels
  • Check: Review application logs for errors
  • Solution: Increase container memory allocation
  • Solution: Restart CyTube periodically during maintenance windows
  • Solution: Optimize channel settings and reduce playlist sizes

Issue: API Quota Exceeded

  • Cause: YouTube API daily quota limit reached
  • Check: Review API usage in Google Cloud Console
  • Check: Monitor video add frequency
  • Solution: Request quota increase from Google
  • Solution: Use multiple API keys with rotation
  • Solution: Cache video metadata to reduce API calls

Getting Help

If you encounter issues not covered here:


Advanced Configuration

Custom Domain Configuration

Use your own domain for better branding:

  1. Configure custom domain in Klutch.sh (see custom domains guide)

  2. Update DNS records to point to your Klutch.sh app

  3. Update environment variable:

    CYTUBE_DOMAIN=https://watch.yourdomain.com
  4. Update config.yaml root-domain settings

  5. Redeploy the application

Custom Theming

Customize CyTube’s appearance:

Global Custom CSS:

Add custom CSS in channel settings:

/* Modern dark theme */
body {
background: #1a1a2e;
color: #eee;
}
#mainpage {
background: #16213e;
}
#chatwrap {
background: #0f3460;
}
.btn-primary {
background: #e94560;
border-color: #e94560;
}
.btn-primary:hover {
background: #c23b52;
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-track {
background: #1a1a2e;
}
::-webkit-scrollbar-thumb {
background: #e94560;
border-radius: 5px;
}

Custom JavaScript:

Add interactive features:

// Auto-greet new users
socket.on('addUser', function(data) {
if (data.rank < 2) {
socket.emit('chatMsg', {
msg: 'Welcome to our channel, ' + data.name + '!',
meta: {}
});
}
});
// Auto-skip videos after voting
var skipVotes = 0;
var skipThreshold = 3;
socket.on('chatMsg', function(data) {
if (data.msg === '!skip') {
skipVotes++;
if (skipVotes >= skipThreshold) {
socket.emit('playNext');
skipVotes = 0;
}
}
});

Media Source Configuration

Custom Direct Media:

For self-hosted videos:

config.yaml
allow-custom-embed: true
custom-embed-domains:
- your-cdn-domain.com
- media.yourdomain.com

FFmpeg Integration:

Enable FFmpeg for processing:

config.yaml
ffmpeg:
enabled: true
ffmpeg-path: '/usr/bin/ffmpeg'
ffprobe-path: '/usr/bin/ffprobe'

Add to Dockerfile:

RUN apk add --no-cache ffmpeg

Advanced Permissions

Custom Permission Scheme:

// Define custom ranks in database
INSERT INTO channel_ranks VALUES
(1, 1, 10), -- Channel 1, User 1, Custom rank 10
(1, 2, 15); -- Channel 1, User 2, Custom rank 15
// Set permissions in channel settings
Add Videos: Rank 10
Delete Videos: Rank 15
Control Playback: Rank 10

Bot Accounts:

Create service accounts for bots:

INSERT INTO users (name, password, global_rank, email, ip, time)
VALUES ('AnnounceBot', 'hashed-password', 1, 'bot@example.com', '127.0.0.1', UNIX_TIMESTAMP() * 1000);
-- Set bot rank in channels
INSERT INTO channel_ranks (channel_id, user_id, rank)
VALUES (1, (SELECT id FROM users WHERE name = 'AnnounceBot'), 3);

SMTP Configuration

Enable email notifications:

config.yaml
mail:
enabled: true
transport: 'smtp'
config:
host: 'smtp.gmail.com'
port: 587
secure: false
auth:
user: 'notifications@yourdomain.com'
pass: 'app-password-here'
from-address: 'noreply@yourdomain.com'

Add environment variables:

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=notifications@yourdomain.com
SMTP_PASSWORD=app-password-here

Redis Integration

For better performance with multiple instances:

config.yaml
redis:
enabled: true
host: 'your-redis-host'
port: 6379
password: 'redis-password'

Deploy Redis on Klutch.sh:

Terminal window
# Create Redis app
# Use official Redis image
# Attach persistent volume to /data
# Configure CyTube to use Redis for sessions

Additional Resources


Conclusion

Deploying CyTube on Klutch.sh provides a powerful synchronized media streaming platform where communities can watch videos together in real-time. With automated Docker detection, persistent storage for channels and chat logs, secure environment variable management, and reliable infrastructure for WebSocket connections, Klutch.sh makes it easy to host your own social viewing platform.

By following this comprehensive guide, you’ve learned how to:

  • Create a production-ready Dockerfile for CyTube with Node.js and dependencies
  • Configure persistent volumes for channel data and chat history
  • Set up environment variables securely for API keys and database credentials
  • Deploy MySQL database for user accounts and channel management
  • Create and manage channels with synchronized video playback
  • Add videos from YouTube, Twitch, Vimeo, and other media sources
  • Manage permissions, moderation, and user ranks
  • Implement chat commands and custom emotes
  • Integrate API keys for media provider support
  • Monitor performance and optimize for your community size
  • Troubleshoot common deployment and operational issues
  • Customize theming and add advanced features

Your CyTube instance is now ready to host watch parties, community viewing sessions, and synchronized streaming events for your audience. As your community grows, you can easily scale your Klutch.sh deployment by allocating additional compute resources and expanding persistent storage for channels and logs. Enjoy building a thriving streaming community with synchronized video playback and real-time chat!