Author | Nejat Hakan |
nejat.hakan@outlook.de | |
PayPal Me | https://paypal.me/nejathakan |
Team Chat Rocket.Chat
Introduction to Self-Hosted Team Communication
Welcome to the comprehensive guide on self-hosting Rocket.Chat, a powerful open-source team communication platform. In an era where digital collaboration is paramount, choosing the right tools for your team's communication needs is crucial. While many cloud-based solutions exist, self-hosting offers unparalleled control, privacy, and customization. This guide is designed for university students and aspiring system administrators who wish to delve into the practical aspects of deploying and managing their own communication infrastructure. We will journey from the fundamental concepts and basic installation to advanced configurations, security hardening, and scaling strategies. Each section is crafted to build upon the previous, providing theoretical knowledge followed by hands-on workshops to solidify your understanding.
Why Self-Host Your Team Chat?
In a world dominated by Software-as-a-Service (SaaS) offerings, the decision to self-host might seem counterintuitive to some. However, for organizations and individuals who prioritize certain aspects of their digital infrastructure, self-hosting provides significant advantages. Let's explore the compelling reasons:
Control and Privacy
Perhaps the most significant advantage of self-hosting is the complete control you retain over your data and the platform itself. When you use a third-party service, your data resides on their servers, subject to their terms of service, privacy policies, and security measures. Self-hosting means your conversations, files, and user information are stored on servers you manage, within jurisdictions you choose. This is particularly critical for organizations dealing with sensitive information, subject to strict data sovereignty regulations (like GDPR, HIPAA), or those with a strong organizational emphasis on privacy. You decide who has access, how data is backed up, and what security protocols are enforced, without relying on external providers whose interests may not always align perfectly with yours.
Customization and Integration
Self-hosting Rocket.Chat opens up a vast array of customization possibilities that are often limited or unavailable in SaaS versions. You can tailor the look and feel to match your organization's branding, modify core functionalities (if you have the development expertise, as it's open-source), and integrate it deeply with your existing internal systems. This could include custom authentication mechanisms (e.g., integrating with your university's LDAP or SSO), linking with internal project management tools, or developing bespoke bots and applications that cater specifically to your team's workflows. The open nature of self-hosted solutions empowers you to create a truly bespoke communication hub.
Cost Savings
While there's an initial investment in terms of server resources (hardware or virtual) and administrative time, self-hosting can lead to significant cost savings in the long run, especially for larger teams or organizations. Many SaaS communication platforms charge per user, per month. As your team grows, these costs can escalate rapidly. With a self-hosted solution, the primary recurring costs are server hosting, domain registration, and potentially bandwidth, which may not scale linearly with the number of users in the same way SaaS fees do. For educational institutions or non-profits with limited budgets but available IT expertise, this can be a game-changer.
Data Ownership
This ties closely with control and privacy but deserves its own mention. When you self-host, you unequivocally own your data. There are no ambiguities about who can access it, analyze it for commercial purposes, or what happens to it if a service provider changes its terms, gets acquired, or goes out of business. Your data retention policies are your own, not dictated by an external entity. This is crucial for intellectual property protection and long-term archival.
Security
While SaaS providers invest heavily in security, self-hosting allows you to implement security measures tailored to your specific threat model and compliance requirements. You can enforce stricter network policies, integrate with your existing security infrastructure (like IDS/IPS, WAFs), and have direct oversight over security audits and incident response. If a vulnerability is discovered in the software, you are not reliant on the SaaS provider's timeline for patching; you can often apply fixes or mitigations more rapidly. Of course, this also means the responsibility for security rests squarely on your shoulders, requiring due diligence and expertise.
Learning and Skill Development
For university students, enthusiasts, or IT professionals looking to expand their skillset, self-hosting projects like Rocket.Chat offer invaluable learning experiences. You'll gain hands-on experience with Linux server administration, Docker, database management (MongoDB), reverse proxies (like Nginx), SSL/TLS certificate management, network configuration, security best practices, and troubleshooting complex systems. These are highly transferable skills in the modern IT landscape.
In summary, self-hosting your team chat platform is a strategic decision that offers profound benefits in terms of control, privacy, customization, cost, data ownership, and security, albeit with the requirement of technical know-how and administrative effort.
What is Rocket.Chat?
Rocket.Chat is a feature-rich, open-source team collaboration platform that enables real-time communication through various channels, including direct messages, private groups, public channels, and video conferencing. It aims to provide a comprehensive communication hub, allowing teams to collaborate efficiently, whether they are in the same office or distributed globally. Being open-source (primarily under the MIT license) means its source code is freely available, allowing for transparency, community contributions, and the ability to self-host and modify the platform.
Key Features
Rocket.Chat boasts an extensive feature set designed to cover diverse communication needs:
- Multiple Communication Modes:
- Channels: Public or private, for topic-based or team-based discussions.
- Teams: A way to group multiple channels and users under a common umbrella, facilitating collaboration across related projects or departments.
- Direct Messages: One-on-one private conversations.
- Discussions: Threaded conversations within channels or direct messages, keeping main chat flows clean.
- Threads: Similar to discussions, allowing focused follow-up conversations without cluttering the main channel.
- File Sharing: Users can easily share documents, images, videos, and other files with previews and search capabilities.
- Voice and Video Conferencing: Integrated or via third-party providers (like Jitsi Meet), enabling face-to-face communication directly within the platform.
- Screen Sharing: Essential for presentations, demonstrations, and collaborative problem-solving.
- Guest Access: Allows external users (clients, partners) to participate in specific channels or discussions with limited permissions.
- Real-time Translation: Facilitates communication between users speaking different languages by translating messages on the fly.
- Powerful Search: Quickly find messages, files, and users across all conversations.
- Notifications: Granular control over desktop, mobile, and email notifications to stay updated without being overwhelmed.
- Customization: Extensive options for theming, custom emojis, custom sounds, and even custom CSS/JavaScript.
- APIs and Webhooks: Robust APIs (REST and Realtime) and support for incoming/outgoing webhooks enable extensive integrations with other tools and services.
- Marketplace: An official marketplace for apps and integrations to extend Rocket.Chat's functionality (e.g., GitHub, GitLab, Jira, Trello).
- Security Features: End-to-End Encryption (E2EE) for sensitive conversations (beta/developing), two-factor authentication (2FA), OAuth support, LDAP/SAML integration, granular permissions, and audit logs.
- Cross-Platform Availability: Clients available for web, desktop (Windows, macOS, Linux), and mobile (iOS, Android).
- Federation: Allows communication between different Rocket.Chat servers, creating a decentralized communication network (evolving feature).
- Data Import/Export: Tools to import data from other platforms like Slack or HipChat, and export user data.
Architecture Overview (Brief)
Rocket.Chat is built primarily using modern web technologies:
- Backend: Node.js with the Meteor framework. Meteor is a full-stack JavaScript platform that simplifies real-time application development.
- Database: MongoDB is the primary database used by Rocket.Chat to store messages, user information, settings, and other application data. MongoDB is a NoSQL document database known for its scalability and flexibility, which suits the dynamic nature of chat applications.
- Frontend: Modern JavaScript frameworks (like React, though historically it used Blaze, Meteor's original UI engine) are used to create a responsive and interactive user interface.
- Real-time Communication: WebSockets are heavily utilized for instant message delivery and presence updates. If WebSockets are unavailable, it can fall back to other transport mechanisms like Long Polling.
When self-hosting, you typically run the Rocket.Chat server application, which connects to a MongoDB database instance. For production environments, this setup is often placed behind a reverse proxy (like Nginx or Apache) for SSL/TLS termination, load balancing, and caching.
Comparison with Alternatives (Brief)
Rocket.Chat competes with both proprietary and other open-source solutions:
- Proprietary (SaaS):
- Slack: Very popular, polished UI, extensive integrations, but can be expensive for large teams and offers less control over data.
- Microsoft Teams: Deeply integrated with the Microsoft 365 ecosystem, feature-rich, often bundled with other Microsoft services. Data control is subject to Microsoft policies.
- Open-Source (Self-hostable):
- Mattermost: A strong competitor, also open-source and self-hostable, written in Go and React. Often positioned as a Slack alternative for enterprises. It has a different feature set and underlying technology stack, leading to different performance characteristics and administrative experiences.
- Zulip: Known for its unique topic-based threading model, which can be very effective for organizing complex conversations. Written in Python (Django).
- Element (Matrix): Part of the decentralized Matrix communication protocol. Element is a client, and Synapse (or Dendrite) is a common homeserver. Focuses heavily on federation and end-to-end encryption.
Rocket.Chat's strengths lie in its comprehensive feature set out-of-the-box, its use of JavaScript across the stack (potentially appealing to a large developer community), and its active community. The choice between these often comes down to specific feature requirements, technical preferences for the underlying stack, desired level of decentralization, and existing infrastructure.
Prerequisites for This Guide
To successfully follow this guide and deploy your own Rocket.Chat server, certain technical skills and system resources are assumed or will need to be acquired. This guide is aimed at university students, so while prior expertise is not expected in all areas, a willingness to learn and troubleshoot is essential.
Technical Skills
- Basic Linux Command Line Proficiency: You should be comfortable navigating the file system, creating/editing files, managing services, and installing software using a package manager (like
apt
for Debian/Ubuntu). Understanding concepts like users, permissions, and basic shell scripting will be beneficial.- Example commands you should recognize or be comfortable learning:
ls
,cd
,mkdir
,rm
,nano
(orvim
),sudo
,apt update
,apt install
,systemctl start/stop/enable/status
.
- Example commands you should recognize or be comfortable learning:
- Understanding of Networking Concepts: Familiarity with IP addresses (IPv4, IPv6), DNS (A records, CNAME records), ports, firewalls, and basic troubleshooting (e.g., using
ping
,curl
,netstat
). - Conceptual Knowledge of Web Servers and Databases: A general understanding of what web servers (like Nginx or Apache) do and how databases (like MongoDB) store information will be helpful, though we will cover specifics.
- Familiarity with Docker (Recommended): While not strictly mandatory for all deployment methods, this guide will heavily feature Docker and Docker Compose for ease of deployment and management. Understanding Docker images, containers, volumes, and networking will be extremely advantageous. We will provide introductory material, but prior exposure is a plus.
- Problem-Solving and Research Skills: Self-hosting often involves troubleshooting unexpected issues. The ability to read log files, search online for solutions (Stack Overflow, official documentation, forums), and systematically diagnose problems is crucial.
- Patience and Persistence: Setting up and maintaining any server application takes time and can sometimes be frustrating. A persistent approach to learning and problem-solving will lead to success.
System Requirements
The specific system requirements for your Rocket.Chat server will depend on the number of users, the level of activity, and the features you intend to use (e.g., video conferencing, large file uploads). However, here are some general guidelines for a small to medium-sized deployment (e.g., up to 50-100 active users):
- Server:
- Operating System: A modern 64-bit Linux distribution is highly recommended. Debian (10 or later) or Ubuntu (18.04 LTS or later) are excellent choices and will be the primary focus of this guide. CentOS/RHEL/AlmaLinux are also viable but may require slight command adjustments.
- CPU: At least 2 CPU cores. More cores will improve performance under load.
- RAM: Minimum 2GB RAM. 4GB RAM is strongly recommended for a smoother experience, especially if running MongoDB and Rocket.Chat on the same server with Docker. For larger deployments, 8GB+ might be necessary.
- Storage: Minimum 20GB of fast SSD storage. The actual storage needed will depend on file uploads and message history retention. SSDs provide significantly better performance for database operations compared to HDDs.
- Internet Connection: A stable internet connection with sufficient bandwidth. You will also need a static IP address (or a dynamic DNS service if your IP changes frequently, though static is preferred for reliability).
- Domain Name: A registered domain name (e.g.,
yourchat.youruniversity.edu
ormyteam.com
) is required to access your Rocket.Chat instance easily and, more importantly, to secure it with SSL/TLS certificates (HTTPS). - Client Machine: A computer with a modern web browser (Chrome, Firefox, Edge, Safari) to access the Rocket.Chat web interface and for server administration (e.g., via SSH).
- Software (to be installed on the server as we proceed):
- Docker and Docker Compose (if using the Docker deployment method).
- A reverse proxy like Nginx (recommended for SSL/TLS and other features).
- Certbot (for obtaining free Let's Encrypt SSL/TLS certificates).
- A firewall utility like
ufw
.
For very small test instances (1-5 users, minimal activity), you might get by with slightly lower specs (e.g., 1 CPU, 1-2GB RAM), but performance will be limited. It's always better to slightly overestimate your resource needs than to underestimate them, especially regarding RAM for database performance. As your user base grows, you may need to scale your server resources or implement a multi-server setup (covered in advanced sections).
This guide will walk you through the installation of necessary software components on your server. Having a clean server instance ready is the ideal starting point.
1. Basic Installation and Configuration
This section will guide you through the fundamental steps of getting your own Rocket.Chat server up and running. We will focus on the most accessible and recommended methods for beginners and students, emphasizing understanding the "why" behind each step. Our primary approach will be using Docker, as it encapsulates dependencies and simplifies both installation and future upgrades.
Understanding Rocket.Chat Deployment Options
Before diving into the installation, it's crucial to understand the various ways Rocket.Chat can be deployed. Each method has its pros and cons, catering to different needs and technical expertise levels.
Docker (Recommended for Beginners and Production)
Docker is an open platform for developing, shipping, and running applications inside containers. Containers package up software and its dependencies, ensuring it runs reliably across different computing environments.
- Pros:
- Simplified Installation: Dependencies (Node.js, specific libraries) are bundled within the Docker image provided by Rocket.Chat. You don't need to install them manually on your host system.
- Isolation: The Rocket.Chat application and its database (MongoDB) can run in isolated containers, preventing conflicts with other software on your server.
- Reproducibility: The environment is consistent, making it easier to troubleshoot and ensuring that what works in development will also work in production.
- Easy Updates: Updating Rocket.Chat often involves simply pulling a new Docker image and restarting the container(s).
- Scalability: Docker environments can be scaled more easily using tools like Docker Swarm or Kubernetes (though this is an advanced topic).
- Community Support: Docker is widely adopted, and there's a wealth of documentation and community support available. Rocket.Chat provides official Docker images.
- Cons:
- Learning Curve: If you're new to Docker, there's a slight learning curve to understand concepts like images, containers, volumes, and Docker Compose.
- Resource Overhead: Docker introduces a small layer of abstraction, which can have a minor performance overhead compared to a bare-metal manual installation, though this is generally negligible for most use cases.
- Disk Space: Docker images can consume significant disk space, especially if you accumulate many unused images.
This guide will primarily focus on Docker deployment due to its overwhelming advantages for most users, especially those learning.
Snap (Easy but Less Flexible)
Snaps are application packages for desktop, cloud, and IoT that are easy to install, secure, cross-platform, and dependency-free. Canonical (the company behind Ubuntu) maintains snaps. Rocket.Chat offers an official Snap package.
- Pros:
- Extreme Simplicity: Installation can be as simple as a single command (e.g.,
sudo snap install rocketchat-server
). - Automatic Updates: Snaps can be configured to update automatically, ensuring you're always running the latest version with security patches.
- Bundled Dependencies: Like Docker, snaps include all necessary dependencies, including a bundled version of MongoDB.
- Security: Snaps run in a sandboxed environment, which can enhance security.
- Extreme Simplicity: Installation can be as simple as a single command (e.g.,
- Cons:
- Less Flexibility: Snaps offer less control over the configuration compared to Docker or manual installations. Customizing paths, specific MongoDB versions, or integrating deeply with existing system services can be challenging.
- Storage Location: Snaps install in a specific system-wide location (
/snap
), which might not align with your preferred filesystem organization. - Bundled MongoDB: While convenient, using the bundled MongoDB might not be ideal if you want to manage your database separately, use an existing MongoDB cluster, or require specific MongoDB configurations.
- Performance: Some users have reported performance issues with the Snap's bundled MongoDB, especially under heavy load, although this can vary.
- Update Control: Automatic updates can sometimes introduce breaking changes or bugs unexpectedly. While convenient, some administrators prefer more control over the update process.
Snap is a good option for a quick trial or for users who prioritize ease of use and automatic updates above all else and don't need deep customization.
Manual Installation (Advanced Control)
This involves manually installing Node.js, MongoDB, and all other dependencies directly on your server's operating system, then downloading and configuring the Rocket.Chat source code or pre-built release.
- Pros:
- Maximum Control and Flexibility: You have granular control over every aspect of the installation, including component versions, file locations, and system integrations.
- Potentially Optimal Performance: By fine-tuning each component and avoiding any containerization overhead, you might achieve slightly better performance (though this often requires significant expertise).
- Deep System Integration: Easier to integrate with existing system monitoring tools, backup solutions, and specific OS-level configurations.
- Cons:
- Complexity: This is the most complex and time-consuming deployment method. It requires a deep understanding of Linux system administration, Node.js, and MongoDB.
- Dependency Management ("Dependency Hell"): Managing dependencies and ensuring compatibility between different software versions can be challenging and error-prone.
- Difficult Updates: Updating Rocket.Chat or its dependencies often involves manual steps and carries a higher risk of breaking the installation if not done carefully.
- Troubleshooting: Diagnosing issues can be harder as problems could stem from the OS, Node.js, MongoDB, Rocket.Chat itself, or interactions between them.
- Security Responsibility: You are fully responsible for securing all components individually.
Manual installation is typically reserved for experienced administrators with very specific requirements or those who want to understand the software at the deepest level. It's generally not recommended for beginners or for most production deployments unless there's a compelling reason.
Cloud Deployments (Marketplaces)
Many cloud providers (AWS, Google Cloud, Azure, DigitalOcean, Linode, etc.) offer Rocket.Chat as a one-click app or marketplace image.
- Pros:
- Rapid Deployment: You can have a Rocket.Chat instance running in minutes with minimal configuration.
- Managed Infrastructure: The underlying server infrastructure is managed by the cloud provider.
- Integration with Cloud Services: Often integrates well with other services offered by the cloud provider (e.g., managed databases, load balancers, backup services).
- Cons:
- Cost: While the Rocket.Chat software is free, you pay for the cloud resources (VM, storage, bandwidth), which can be more expensive than a self-managed VPS from a budget provider.
- Potentially Less Control: Depending on the marketplace offering, you might have less control than a manual or Docker installation on your own VPS. Some marketplace images might be pre-configured in ways that are not ideal for your specific needs.
- Vendor Lock-in (Mild): While Rocket.Chat itself is portable, relying heavily on specific cloud provider services can create a degree of vendor lock-in.
- Black Box Nature: Sometimes, these one-click deployments obscure the underlying configuration, making troubleshooting or advanced customization harder.
Marketplace deployments can be a good starting point if you're already invested in a particular cloud ecosystem and prefer a managed approach, but it's still beneficial to understand the underlying components, which this guide will cover.
Our Recommendation: For this guide, and for most self-hosting scenarios balancing ease of use, control, and scalability, Docker (specifically with Docker Compose) is the recommended path. It provides a good abstraction layer, simplifies management, and is well-supported by the Rocket.Chat community.
Choosing Your Server Environment
Before you can install Rocket.Chat, you need a server. This server will be the home for your communication platform. Several factors go into choosing the right environment.
Operating System Choices (Linux Focus - Ubuntu/Debian Recommended)
Rocket.Chat is designed to run on various operating systems, but Linux is the most common and well-supported environment for server deployments.
- Why Linux?
- Stability and Reliability: Linux is renowned for its stability, making it ideal for running server applications that need to be available 24/7.
- Performance: Linux is generally more efficient in terms of resource usage compared to Windows Server for this type of application.
- Security: Linux has a robust security model, and a vast community constantly works on identifying and patching vulnerabilities.
- Cost: Most Linux distributions are free and open-source, reducing licensing costs.
- Tooling and Community: The command-line interface (CLI), package managers, and extensive community support make Linux a powerful platform for developers and system administrators. Most guides and tutorials (including this one) will assume a Linux environment.
- Recommended Distributions:
- Ubuntu Server: Particularly versions like 20.04 LTS or 22.04 LTS (Long Term Support). Ubuntu is known for its user-friendliness, extensive documentation, large software repositories, and strong community support. LTS releases receive security updates for 5 years (or more with Extended Security Maintenance), making them suitable for production servers.
- Debian: Debian is the upstream distribution for Ubuntu and is known for its stability, commitment to free software, and rigorous testing. Versions like Debian 10 (Buster) or Debian 11 (Bullseye) are excellent choices. It's slightly more "bare-bones" than Ubuntu initially, which some experienced users prefer.
- Other Linux Distributions:
- CentOS Stream / RHEL / AlmaLinux / Rocky Linux: These are also popular server distributions, particularly in enterprise environments. While Rocket.Chat can run on them, package manager commands (
yum
ordnf
instead ofapt
) and some configuration file paths might differ from what's presented in this guide.
- CentOS Stream / RHEL / AlmaLinux / Rocky Linux: These are also popular server distributions, particularly in enterprise environments. While Rocket.Chat can run on them, package manager commands (
- Windows Server: While it's technically possible to run Rocket.Chat on Windows (e.g., using Docker Desktop for Windows with WSL2, or even a manual Node.js setup), it's generally not recommended for production due to potential performance issues, compatibility challenges, and less community support for this specific deployment scenario.
- macOS: Suitable for development or testing purposes (e.g., using Docker Desktop for Mac), but not for production server deployments.
For this guide, we will assume you are using Ubuntu 20.04 LTS / 22.04 LTS or Debian 10 / 11. Commands will be tailored for these systems using the apt
package manager.
Virtual Private Server (VPS) vs. Bare Metal
- Virtual Private Server (VPS):
- A VPS is a virtual machine sold as a service by an internet hosting provider. You get a dedicated portion of a physical server's resources (CPU, RAM, storage) that functions like a standalone server.
- Pros:
- Cost-Effective: Generally cheaper than dedicated bare metal servers, especially for smaller needs.
- Scalability: Easy to scale resources up or down (e.g., add more RAM or CPU) as your needs change, often with minimal downtime.
- Accessibility: Many providers worldwide (DigitalOcean, Linode, Vultr, Hetzner, OVH, AWS Lightsail, Google Cloud Compute Engine, Azure VMs).
- Management Features: Providers often offer control panels for managing the VPS (rebooting, backups, snapshots).
- Cons:
- "Noisy Neighbors": Performance can sometimes be affected by other VPS instances on the same physical hardware if the provider oversells resources (less common with reputable providers).
- Resource Limits: You are still sharing underlying hardware, so you don't have the absolute raw performance of a dedicated machine.
- Bare Metal Server (Dedicated Server):
- A physical server that is entirely dedicated to your use. You have full access to all its hardware resources.
- Pros:
- Maximum Performance: All hardware resources are exclusively yours, offering the best possible performance.
- Full Control: Complete control over hardware and software configurations.
- Predictable Performance: No "noisy neighbor" effect.
- Cons:
- Cost: Significantly more expensive than VPS.
- Management Overhead: You are responsible for all hardware management (or rely on the provider's "remote hands" services, which can be costly). If a component fails, replacement might take time.
- Less Flexible Scaling: Scaling up often requires physical hardware upgrades or migrating to a new server.
Recommendation: For most self-hosting projects, especially when starting, a VPS is the most practical and cost-effective choice. It offers a good balance of performance, control, and scalability. As your Rocket.Chat instance grows to support thousands of users, you might consider bare metal or more advanced cloud solutions, but a VPS will serve well for the scope of this guide (and beyond for many). Choose a reputable VPS provider that offers good network connectivity and SSD storage.
Resource Allocation (CPU, RAM, Storage)
As mentioned in the prerequisites, careful resource allocation is key.
- CPU:
- Rocket.Chat benefits from multiple cores, especially for handling concurrent connections and background tasks.
- Minimum: 2 vCPUs (virtual CPUs on a VPS).
- Recommended for small/medium teams (up to ~100 active users): 2-4 vCPUs.
- Larger deployments: 4+ vCPUs.
- The clock speed of the cores also matters. Modern CPUs (e.g., Intel Xeon E5 series, AMD EPYC) are generally sufficient.
- RAM (Memory):
- This is often the most critical resource. Rocket.Chat and MongoDB (its database) can be memory-intensive. Insufficient RAM leads to swapping (using disk as slow RAM), which drastically degrades performance.
- Absolute Minimum (for testing/very small instance, not recommended): 2GB (this assumes Rocket.Chat and MongoDB are on the same server). You might encounter performance issues.
- Recommended Minimum for Production (small team): 4GB. This provides enough room for the OS, Rocket.Chat, MongoDB, a reverse proxy, and some caching.
- Medium Teams (~100-500 active users): 8GB - 16GB.
- Larger Deployments: 16GB+.
- Note: If you run MongoDB on a separate server, the RAM requirements for the Rocket.Chat application server can be slightly lower, but the MongoDB server will need ample RAM (ideally enough to hold its working set in memory).
- Storage:
- Type: SSD (Solid State Drive) is highly recommended over HDD (Hard Disk Drive). Database operations (reads/writes by MongoDB) and application responsiveness are significantly faster on SSDs. NVMe SSDs are even faster but usually more expensive.
- Capacity:
- Operating System and Software: ~10-15 GB.
- Rocket.Chat Application & Logs: Relatively small, a few GB.
- MongoDB Database: This will grow with the number of users, messages, and channels. Starts small but can grow to many GBs over time.
- File Uploads: This is usually the biggest consumer of storage. Consider how much data your users will upload (images, documents, videos). If you expect large volumes, you might need hundreds of GBs or even consider using external object storage (like AWS S3, MinIO - an advanced topic).
- Minimum: 20-30GB SSD (for very small teams with minimal file sharing and short message retention).
- Recommended Start: 50-80GB SSD. This provides room for growth.
- Plan for Growth: Monitor disk usage and be prepared to expand storage or implement strategies for managing old data (e.g., pruning old files, archiving messages).
- Network Bandwidth:
- Depends on user activity, file sharing, and video conferencing usage.
- Most VPS providers offer generous bandwidth allowances (e.g., 1TB+ per month).
- Ensure your provider has good peering and low latency to your primary user base. A 100 Mbps connection is a good start; 1 Gbps is better for larger teams or heavy media usage.
Example VPS Configuration for a Team of ~50 Active Users: * 2-4 vCPUs * 4-8 GB RAM * 50-80 GB SSD Storage * 1 TB+ Bandwidth
When selecting a VPS provider, compare pricing, features, locations (choose a location geographically close to your users for lower latency), and reviews. DigitalOcean, Linode, Vultr, Hetzner Cloud are popular choices offering good value.
Docker Deployment Step-by-Step
As established, Docker provides an excellent balance of ease of use, consistency, and control for deploying Rocket.Chat. This section will walk you through setting up Rocket.Chat using Docker and Docker Compose. Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application's services, networks, and volumes, and then with a single command, you create and start all the services from your configuration.
We will deploy two main services:
- MongoDB: The database where Rocket.Chat stores all its data.
- Rocket.Chat: The application server itself.
These will run in separate containers but will be able to communicate with each other over a Docker-managed network.
Installing Docker and Docker Compose
Before you can deploy Rocket.Chat, you need to install Docker Engine and Docker Compose on your server. We'll use the official Docker repositories to ensure we get the latest stable versions. These instructions are for Ubuntu/Debian.
Workshop Installing Docker and Docker Compose
Objective
To install Docker Engine and Docker Compose on your Linux server (Ubuntu/Debian) so that it is ready for deploying containerized applications like Rocket.Chat.
Prerequisites
- A server running a supported 64-bit version of Ubuntu (e.g., 20.04 LTS, 22.04 LTS) or Debian (e.g., 10, 11).
- Access to the server via SSH with a user account that has
sudo
privileges. - An internet connection on the server to download packages.
Steps
1. Update System Packages
First, ensure your system's package list and installed packages are up to date. This is good practice before installing new software.
sudo apt update
: Refreshes the local package list from the repositories defined in/etc/apt/sources.list
and/etc/apt/sources.list.d/
.sudo apt upgrade -y
: Upgrades all currently installed packages to their newest versions. The-y
flag automatically answers "yes" to any prompts.
2. Install Docker Engine
We will install Docker Engine from Docker's official APT repository. This ensures you get the latest version and that it's maintained by Docker.
-
Install prerequisite packages: These packages allow
apt
to use repositories over HTTPS.sudo apt install -y apt-transport-https ca-certificates curl software-properties-common gnupg lsb-release
apt-transport-https
: Allows theapt
package manager to retrieve packages over HTTPS.ca-certificates
: Allows your system to check security certificates (like those used by HTTPS).curl
: A command-line tool for transferring data with URLs, used here to download the GPG key.software-properties-common
: Provides scripts for managing software repositories, includingadd-apt-repository
.gnupg
: GNU Privacy Guard, used for managing GPG keys for verifying package authenticity.lsb-release
: Provides information about the Linux Standard Base and distribution.
-
Add Docker's official GPG key: This key is used to verify that the Docker packages you download are authentic and haven't been tampered with.
Or for Debian:curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
curl -fsSL ...
: Downloads the GPG key.-f
fails silently on server errors,-s
is silent mode,-S
shows an error if it fails,-L
follows redirects.sudo gpg --dearmor -o ...
: Converts the key from ASCII-armored format to binary format and saves it to the specified keyring file.
-
Set up the stable Docker repository: This command adds Docker's official repository to your system's APT sources. For Ubuntu:
For Debian:echo \ "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
echo \ "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
echo "..."
: Prints the repository string.arch=$(dpkg --print-architecture)
: Dynamically gets your system's architecture (e.g.,amd64
).signed-by=...
: Tellsapt
to use the GPG key we added earlier to verify packages from this repository.$(lsb_release -cs)
: Gets your distribution's codename (e.g.,focal
for Ubuntu 20.04,bullseye
for Debian 11).sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
: Writes the repository string to a new sources list file for Docker and suppresses output.
-
Update the package index again: Now that the Docker repository is added, update
apt
's package list. -
Install Docker Engine, CLI, containerd, and Docker Compose plugin:
docker-ce
: Docker Community Edition (the Docker Engine itself).docker-ce-cli
: Docker Community Edition Command Line Interface.containerd.io
: An industry-standard core container runtime.docker-compose-plugin
: Installs Docker Compose as a plugin, allowing you to usedocker compose
(with a space) instead of the olderdocker-compose
(with a hyphen). This is the modern way.
3. Start and Enable Docker Service
The Docker service should start automatically after installation. You can check its status and enable it to start on boot if it isn't already.
-
Check Docker status:
You should see output indicating that the service isactive (running)
. Pressq
to exit the status view. -
Enable Docker to start on boot (usually done automatically, but good to ensure):
4. Verify Docker Installation
Run a simple test image to confirm Docker is working correctly.
hello-world
image (if not already present) and run it in a container. You should see a message starting with "Hello from Docker!" indicating that your installation appears to be working correctly.
- Optional Add your user to the
docker
group: By default, running Docker commands requiressudo
. To run Docker commands withoutsudo
, add your user to thedocker
group.usermod -aG docker
: Modifies the user, appending (-a
) them to the supplementary group (-G
)docker
.${USER}
: An environment variable that automatically expands to your current username. Important: After running this command, you need to log out and log back in (or reboot, or runnewgrp docker
in your current shell, though a full logout/login is more reliable) for the group membership change to take effect. For security reasons, be aware that users in thedocker
group have privileges equivalent to root access to the host system.
5. Install Docker Compose (Standalone - Alternative/Legacy)
The docker-compose-plugin
installed in step 2 provides docker compose
(with a space). If you prefer or need the standalone docker-compose
(with a hyphen), you can install it separately. However, the plugin is the recommended approach for newer Docker versions. If you already have docker compose
working, you can skip this step or choose one method.
-
Download the latest stable release of Docker Compose (standalone): Check the Docker Compose releases page on GitHub (https://github.com/docker/compose/releases) for the latest version number. Replace
vX.Y.Z
with the actual version (e.g.,v2.24.6
).LATEST_COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') echo "Latest Docker Compose version: $LATEST_COMPOSE_VERSION" sudo curl -L "https://github.com/docker/compose/releases/download/${LATEST_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
- The first command fetches the latest version tag from GitHub API.
uname -s
: Gets the kernel name (e.g.,Linux
).uname -m
: Gets the machine hardware name (e.g.,x86_64
).- This downloads the binary to
/usr/local/bin/docker-compose
.
-
Apply executable permissions to the binary:
-
Verify standalone Docker Compose installation (if installed):
This should print the version number, e.g.,Docker Compose version vX.Y.Z
.
Note: For the rest of this guide, we will primarily use docker compose
(with a space), assuming you installed the plugin. If you installed the standalone version and not the plugin, you would use docker-compose
(with a hyphen) instead.
Conclusion
You have successfully installed Docker Engine and Docker Compose on your server. Your system is now prepared to run containerized applications. You verified the installation by running the hello-world
image and optionally configured Docker to be run without sudo
by your user.
Creating a Docker Compose File for Rocket.Chat and MongoDB
Docker Compose uses a YAML file (typically named docker-compose.yml
or docker-compose.yaml
) to define a multi-container application. This file describes the services, networks, volumes, and other configurations needed to run your application.
For Rocket.Chat, we need at least two services:
rocketchat
: The Rocket.Chat application server itself.mongo
: The MongoDB database server.
We'll also define:
- Volumes: To persist data. If containers are deleted, data stored in volumes remains. This is crucial for your database and file uploads.
- Networks: To allow containers to communicate with each other securely. Docker Compose creates a default network for the application.
- Ports: To expose the Rocket.Chat application to the outside world (e.g., on port 3000).
- Environment Variables: To configure the services (e.g., database connection details, Rocket.Chat settings).
Workshop Creating Your First Rocket.Chat Docker Compose File
Objective
To create a docker-compose.yml
file that defines the Rocket.Chat application service and its required MongoDB database service, along with necessary configurations for data persistence and networking.
Prerequisites
- Docker Engine and Docker Compose installed and working (from the previous workshop).
- Access to your server via SSH.
- A text editor available on your server (e.g.,
nano
,vim
).
Understanding the Components
version
: Specifies the Docker Compose file format version. Version3.8
is a good modern choice.services
: Defines the different containers that make up your application.image
: Specifies the Docker image to use for the service (e.g.,mongo:5.0
orrocketchat/rocket.chat:latest
). Using specific versions (likemongo:5.0
orrocketchat/rocket.chat:6.5.2
) is generally recommended for production stability overlatest
to avoid unexpected major upgrades.container_name
: Assigns a specific name to the container (optional but helpful).restart
: Defines the restart policy (e.g.,unless-stopped
ensures the container restarts automatically unless manually stopped).volumes
: Mounts host paths or named volumes into the container to persist data.- Named Volumes: Managed by Docker, stored in a Docker-controlled area (e.g.,
/var/lib/docker/volumes/
). This is the preferred way. - Bind Mounts: Maps a directory on the host system directly into the container (e.g.,
./data/mongo:/data/db
).
- Named Volumes: Managed by Docker, stored in a Docker-controlled area (e.g.,
ports
: Exposes container ports to the host machine (e.g.,3000:3000
maps port 3000 on the host to port 3000 in the container).environment
: Sets environment variables inside the container. These are used to configure the application.command
: Overrides the default command executed when the container starts.depends_on
: Specifies dependencies between services (e.g., ensuresmongo
starts beforerocketchat
attempts to connect).networks
: Connects services to specific Docker networks.
volumes
(top-level): Defines named volumes that can be used by services.networks
(top-level): Defines custom Docker networks.
Steps
1. Create a Project Directory
It's good practice to keep your Docker Compose files and related configurations organized. Create a directory for your Rocket.Chat project.
mkdir ~/rocketchat-server
: Creates a directory namedrocketchat-server
in your home directory.cd ~/rocketchat-server
: Changes the current directory to the newly created one. All subsequent commands in this workshop assume you are in this directory.
2. Create the docker-compose.yml
File
Use a text editor to create and open a new file named docker-compose.yml
.
vim
or any other editor you prefer.)
3. Define the MongoDB Service
Add the following configuration for the MongoDB service. Rocket.Chat requires MongoDB. We'll use version 5.0 of MongoDB, as it's widely compatible and stable with recent Rocket.Chat versions. Always check the Rocket.Chat documentation for recommended MongoDB versions for the specific Rocket.Chat version you intend to deploy.
version: '3.8'
services:
mongo:
image: mongo:5.0 # Using MongoDB 5.0. Pinning versions is good practice.
container_name: rocketchat_mongo
restart: unless-stopped
volumes:
- mongo_data:/data/db # Named volume for MongoDB data
- mongo_config:/data/configdb # Named volume for MongoDB configuration
command: mongod --replSet rs0 --oplogSize 128 # Enable replica set for future HA and change streams
networks:
- rocketchat_net
image: mongo:5.0
: Pulls the official MongoDB image, tag5.0
.container_name: rocketchat_mongo
: Gives a readable name to this container.restart: unless-stopped
: Ensures MongoDB restarts if it crashes or the server reboots, unless you explicitly stop it.volumes
:mongo_data:/data/db
: Maps a Docker named volume calledmongo_data
to the/data/db
directory inside the container, which is where MongoDB stores its database files.mongo_config:/data/configdb
: Maps a Docker named volume calledmongo_config
to/data/configdb
.
command: mongod --replSet rs0 --oplogSize 128
:- This command starts the MongoDB daemon (
mongod
). --replSet rs0
: Initializes MongoDB with a replica set namedrs0
. Even for a single MongoDB instance, enabling replica set mode is crucial for Rocket.Chat because it relies on MongoDB's "oplog" (operations log) for real-time updates and change streams. This is essential for features like multi-instance scaling and observing database changes.--oplogSize 128
: Sets the oplog size to 128 MB. Adjust this based on your expected activity. For very high-traffic sites, you might need a larger oplog.
- This command starts the MongoDB daemon (
networks: - rocketchat_net
: Connects this service to a custom network namedrocketchat_net
.
4. Define the Rocket.Chat Service
Now, add the configuration for the Rocket.Chat service to the same docker-compose.yml
file, below the mongo
service definition.
rocketchat:
image: rocketchat/rocket.chat:latest # Or a specific version like rocketchat/rocket.chat:6.5.2
container_name: rocketchat_app
restart: unless-stopped
volumes:
- uploads:/app/uploads # Named volume for file uploads
environment:
- PORT=3000
- ROOT_URL=http://localhost:3000 # IMPORTANT: Change this later to your actual domain
- MONGO_URL=mongodb://mongo:27017/rocketchat?replicaSet=rs0
- MONGO_OPLOG_URL=mongodb://mongo:27017/local?replicaSet=rs0
# Optional: For email configuration (SMTP). Replace with your actual SMTP details.
# - MAIL_URL=smtp://user:pass@smtp.example.com:587/
ports:
- "3000:3000" # Expose port 3000 on the host, mapped to port 3000 in the container
depends_on:
mongo:
condition: service_started # Waits for mongo service to report it has started
networks:
- rocketchat_net
image: rocketchat/rocket.chat:latest
: Pulls the official Rocket.Chat image. For production, it's highly recommended to pin to a specific version (e.g.,rocketchat/rocket.chat:6.5.2
) to prevent unexpected breaking changes fromlatest
. You can find available tags on Docker Hub.container_name: rocketchat_app
: A readable name for the Rocket.Chat application container.restart: unless-stopped
: Same restart policy as MongoDB.volumes
:uploads:/app/uploads
: Maps a Docker named volume calleduploads
to/app/uploads
inside the container. This is where Rocket.Chat stores uploaded files.
environment
:PORT=3000
: Tells Rocket.Chat to listen on port 3000 inside the container.ROOT_URL=http://localhost:3000
: This is a critical setting. It tells Rocket.Chat its own accessible URL. For initial local testing,http://localhost:3000
is fine. You MUST change this to your public domain name (e.g.,http://chat.yourdomain.com
orhttps://chat.yourdomain.com
after setting up a reverse proxy and SSL) before going live. IncorrectROOT_URL
can lead to issues with asset loading, notifications, and integrations.MONGO_URL=mongodb://mongo:27017/rocketchat?replicaSet=rs0
: The connection string for Rocket.Chat to connect to the MongoDB service.mongo
: This refers to the service name of our MongoDB container. Docker Compose provides DNS resolution between services on the same network.27017
: The default MongoDB port.rocketchat
: The name of the database Rocket.Chat will use.?replicaSet=rs0
: Tells the MongoDB driver to connect to the replica set namedrs0
(which we configured for themongo
service).
MONGO_OPLOG_URL=mongodb://mongo:27017/local?replicaSet=rs0
: The connection string for accessing the MongoDB oplog. This is essential for real-time features and scalability. Thelocal
database is where MongoDB stores the oplog.# - MAIL_URL=...
: This is commented out for now. Later, you'll configure this with your SMTP server details if you want Rocket.Chat to send emails (e.g., for password resets, notifications).
ports
:"3000:3000"
: Maps port 3000 on your host server to port 3000 inside the Rocket.Chat container. This means you can access Rocket.Chat by navigating tohttp://your_server_ip:3000
.
depends_on
:mongo: condition: service_started
: Tells Docker Compose that therocketchat
service depends on themongo
service. It will wait until themongo
service is considered "started" before startingrocketchat
. Whileservice_started
doesn't guarantee MongoDB is fully ready to accept connections, it's a good first step. For more robust startup ordering, a script likewait-for-it.sh
ordockerize
might be used within the Rocket.Chat container's entrypoint, but the official image handles retries.
networks: - rocketchat_net
: Connects this service to therocketchat_net
network as well.
5. Define Networks and Volumes (Top-Level)
At the end of your docker-compose.yml
file (at the same indentation level as version
and services
), define the named volumes and the custom network used by your services.
volumes
: This section declares the named volumes. Docker will manage their creation and storage.mongo_data:
mongo_config:
uploads:
networks
:rocketchat_net:
: Declares a custom network namedrocketchat_net
.driver: bridge
: Specifies that this network should use the defaultbridge
driver, which creates a private internal network for the containers. Services on the same bridge network can communicate with each other using their service names as hostnames.
6. Full docker-compose.yml
Example
Your complete docker-compose.yml
file should now look like this:
version: '3.8'
services:
mongo:
image: mongo:5.0
container_name: rocketchat_mongo
restart: unless-stopped
volumes:
- mongo_data:/data/db
- mongo_config:/data/configdb
command: mongod --replSet rs0 --oplogSize 128
networks:
- rocketchat_net
rocketchat:
image: rocketchat/rocket.chat:latest # Consider pinning to a specific version, e.g., 6.5.2
container_name: rocketchat_app
restart: unless-stopped
volumes:
- uploads:/app/uploads
environment:
- PORT=3000
- ROOT_URL=http://localhost:3000 # IMPORTANT: Change for production!
- MONGO_URL=mongodb://mongo:27017/rocketchat?replicaSet=rs0
- MONGO_OPLOG_URL=mongodb://mongo:27017/local?replicaSet=rs0
# - MAIL_URL=smtp://user:pass@smtp.example.com:587/
ports:
- "3000:3000"
depends_on:
mongo:
condition: service_started
networks:
- rocketchat_net
volumes:
mongo_data:
mongo_config:
uploads:
networks:
rocketchat_net:
driver: bridge
Save the file and exit the text editor (for nano
: Ctrl+X
, then Y
, then Enter
).
Conclusion
You have now created a docker-compose.yml
file that defines a two-service Rocket.Chat application: a MongoDB database and the Rocket.Chat server. This file includes configurations for data persistence using named volumes, inter-service communication using a custom network, and initial environment variables. This file is the blueprint Docker Compose will use to launch and manage your Rocket.Chat instance. In the next workshop, you will use this file to start the services.
Launching Rocket.Chat with Docker Compose
With your docker-compose.yml
file ready, launching Rocket.Chat is straightforward. Docker Compose will read this file, pull the necessary Docker images (if they don't exist locally), create the defined networks and volumes, and then start the containers for your services.
A crucial step after starting the mongo
container for the first time with --replSet rs0
is to initialize the replica set. The Rocket.Chat container includes logic to attempt this initialization, but sometimes it might be necessary to do it manually if issues arise or if you want more control. For simplicity in this initial launch, we'll rely on the Rocket.Chat container to handle it. The MONGO_OPLOG_URL
setting is key for this.
Workshop Launching and Accessing Rocket.Chat
Objective
To launch the Rocket.Chat and MongoDB services using the docker-compose.yml
file created previously, and to verify that Rocket.Chat is running and accessible via a web browser. We will also cover initializing the MongoDB replica set, which is essential for Rocket.Chat's functionality.
Prerequisites
- Docker Engine and Docker Compose installed and working.
- A
docker-compose.yml
file configured for Rocket.Chat and MongoDB in a project directory (e.g.,~/rocketchat-server/docker-compose.yml
) as created in the previous workshop. - Your server's firewall (if enabled) must allow incoming connections on port 3000 (or whichever port you mapped for Rocket.Chat). For example, with
ufw
:sudo ufw allow 3000/tcp
. We will cover firewalls in more detail later.
Steps
1. Navigate to Your Project Directory
Open your terminal and navigate to the directory where your docker-compose.yml
file is located.
2. Start Rocket.Chat Services
Use the docker compose up
command to start your services.
docker compose
: The command for Docker Compose (if you installed the plugin). Usedocker-compose
(with hyphen) if you installed the standalone version.up
: This sub-command builds (if necessary), creates, starts, and attaches to containers for a service.-d
: Runs containers in "detached" mode (in the background). Without-d
, the logs from all containers would stream to your terminal, and pressingCtrl+C
would stop the containers.
When you run this command for the first time, Docker Compose will:
- Create Networks: The
rocketchat_net
network will be created. - Create Volumes: The
mongo_data
,mongo_config
, anduploads
volumes will be created. - Pull Images: Docker will download the
mongo:5.0
androcketchat/rocket.chat:latest
(or your specified version) images from Docker Hub if they are not already present on your system. This might take a few minutes depending on your internet speed. - Create and Start Containers: Containers for
mongo
and thenrocketchat
will be created and started based on yourdocker-compose.yml
configuration.
You should see output similar to this (names might vary slightly):
[+] Running 4/4
✔ Network rocketchat-server_rocketchat_net Created 0.1s
✔ Volume "rocketchat-server_mongo_data" Created 0.0s
✔ Volume "rocketchat-server_mongo_config" Created 0.0s
✔ Volume "rocketchat-server_uploads" Created 0.0s
[+] Running 3/3
✔ Container rocketchat_mongo Started 0.8s
✔ Container rocketchat_app Started 0.9s
3. Initialize MongoDB Replica Set
The Rocket.Chat container, when started with MONGO_OPLOG_URL
and MONGO_URL
containing ?replicaSet=rs0
, should automatically attempt to connect to the MongoDB instance and initiate the replica set rs0
if it's not already configured. This process might take a minute or two after the MongoDB container starts.
You can check the logs of the Rocket.Chat container to see if this initialization is successful or if there are any errors.
docker compose logs
: Fetches the logs of services.-f
: Follow log output (streams new logs as they arrive).rocketchat
: The name of the service whose logs you want to see.
Look for messages related to MongoDB connection and replica set initialization. You might see lines like:
➔ +------------------------------------------------------------------+
➔ | MONGO REPLICA SET INIT |
➔ +------------------------------------------------------------------+
➔ | This MONGO_URL "mongodb://mongo:27017/rocketchat?replicaSet=rs0" |
➔ | has "replicaSet=rs0" then I will try to init the replica set. |
➔ | |
➔ | Probing mongo.. done |
➔ | Status of mongo replica set: "not initiated" |
➔ | Setting up mongo replica set.. Done! |
➔ | Status of mongo replica set: "healthy" |
➔ +------------------------------------------------------------------+
If initialization fails or hangs (less common with modern Rocket.Chat images): Sometimes, especially on slower systems or if there's a race condition, the automatic initialization might need a nudge. You can manually initiate the replica set by connecting to the MongoDB container.
-
Connect to the
mongo
container's shell:docker compose exec
: Executes a command in a running container.mongo
: The service name of your MongoDB container.mongosh
: The MongoDB shell client (for MongoDB 5.0+; usemongo
for older versions).
-
Inside the
mongosh
shell, initiate the replica set:- This command initializes a replica set named
rs0
with one member: the current MongoDB instance (which Docker Compose makes resolvable asmongo
on port27017
within the Docker network).
- This command initializes a replica set named
-
Check the replica set status (still in
You should see output indicating the replica set status, including the state of its members (e.g.,mongosh
):PRIMARY
). -
Exit
After manual initialization, restart the Rocket.Chat container so it can connect to the now-initialized replica set: Then check its logs again:mongosh
:docker compose logs -f rocketchat
.
4. Monitor Logs (Optional but Recommended)
It's good practice to monitor the logs of your containers for a few minutes after starting them to catch any startup errors.
-
View logs for Rocket.Chat:
Look for messages indicating that Rocket.Chat has started successfully and is listening on port 3000. You might see something like:The➔ | SERVER RUNNING | ➔ +----------------------------------------------------------+ ➔ | | ➔ | Rocket.Chat Version: X.Y.Z | ➔ | NodeJS Version: vA.B.C | ➔ | MongoDB Version: D.E.F | ➔ | MongoDB Engine: wiredTiger | ➔ | Platform: linux | ➔ | Process Port: 3000 | ➔ | Site URL: http://localhost:3000 | ➔ | ReplicaSet OpLog: Enabled | ➔ | Commit Hash: abcdef12345 | ➔ | Commit Branch: HEAD | ➔ | | ➔ +----------------------------------------------------------+
Site URL
should match yourROOT_URL
setting. TheReplicaSet OpLog: Enabled
is important. PressCtrl+C
to stop following logs. -
View logs for MongoDB:
Look for messages indicating that MongoDB is ready for connections. PressCtrl+C
to stop following logs. -
View logs for all services:
5. Check Running Containers
You can verify that your containers are running using the docker compose ps
or docker ps
command.
docker-compose.yml
:
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
rocketchat_app rocketchat/rocket.chat:latest "node main.js" rocketchat 5 minutes ago Up 5 minutes 0.0.0.0:3000->3000/tcp
rocketchat_mongo mongo:5.0 "docker-entrypoint.s…" mongo 5 minutes ago Up 5 minutes 27017/tcp
rocketchat_mongo
and rocketchat_app
with a STATUS
of Up ...
. Note the PORTS
column for rocketchat_app
shows 0.0.0.0:3000->3000/tcp
, meaning port 3000 on all host network interfaces is mapped to port 3000 in the rocketchat_app
container.
6. Access Rocket.Chat in Your Browser
Open your web browser and navigate to your server's IP address on port 3000:
http://your_server_ip:3000
Replace your_server_ip
with the actual public IP address of your server.
If everything is configured correctly, you should see the Rocket.Chat setup wizard page, prompting you to create an administrator account and configure your workspace.
If you cannot access Rocket.Chat:
* Firewall: Ensure your server's firewall (e.g., ufw
) allows traffic on port 3000.
* Check ufw
status: sudo ufw status
* If port 3000 is not allowed: sudo ufw allow 3000/tcp
* Then sudo ufw reload
or sudo ufw enable
if it was disabled.
* Docker Logs: Check docker compose logs rocketchat
and docker compose logs mongo
for any error messages.
* ROOT_URL
: For now, http://your_server_ip:3000
in your browser should work even if ROOT_URL
is http://localhost:3000
, but some assets might not load correctly or redirects might be problematic. The setup wizard should still appear. We will correct ROOT_URL
later when setting up a domain and reverse proxy.
* Docker ps
: Ensure containers are actually running (docker compose ps
).
* Server Resources: Ensure your server has enough RAM (at least 2GB, 4GB recommended). If RAM is too low, services might fail to start or crash. Check with free -h
.
7. Stop Rocket.Chat Services (When Needed)
To stop your Rocket.Chat application:
docker-compose.yml
unless they are marked as external.
* To stop without removing named volumes (recommended to preserve data):
Actually, docker compose down
does not remove named volumes by default. To remove named volumes along with containers and networks, you would use docker compose down -v
or docker compose down --volumes
. So, docker compose down
is safe for your data in named volumes.
If you want to stop the containers without removing them (so they can be started again faster with docker compose up -d
or docker compose start
):
And to start them again:
Conclusion
You have successfully launched Rocket.Chat and MongoDB using Docker Compose. You learned how to start the services, check their status and logs, and perform the crucial MongoDB replica set initialization. You should now be able to access the Rocket.Chat setup wizard in your web browser. Remember that for now, access is via HTTP on port 3000 using the server's IP address. In later sections, we will secure this with HTTPS and a custom domain name.
Initial Rocket.Chat Setup Wizard
Once you've successfully launched Rocket.Chat using Docker Compose and can access it via http://your_server_ip:3000
in your web browser, you'll be greeted by the Rocket.Chat Setup Wizard. This wizard guides you through the initial configuration of your workspace, including creating the first administrator account, setting organization details, and some basic workspace settings. Completing this wizard is essential before you can start using your Rocket.Chat instance.
The steps and appearance of the wizard might vary slightly between Rocket.Chat versions, but the core information requested remains largely the same.
Admin Account Creation
This is the very first and most crucial step. You will create the primary administrator account for your Rocket.Chat server. This account will have full privileges to manage all aspects of the workspace, including users, permissions, settings, and integrations.
- Information Required:
- Administrator Name: Your full name or a display name for the admin user.
- Username: A unique username for the admin account (e.g.,
admin
,root
, or your preferred username). This is what you'll use to log in. - Email: A valid email address for the admin account. This will be used for notifications, password resets, and official communications if you register your server.
- Password: A strong, unique password for the admin account. Choose a password that is difficult to guess and store it securely. Rocket.Chat usually indicates password strength.
Security Note: The administrator account is powerful. Protect its credentials carefully. Consider using a password manager to generate and store a strong password.
Organization Information
Next, Rocket.Chat will ask for some information about your organization. This information is used for various purposes, including display within the workspace, communication with Rocket.Chat (if you choose to register), and understanding how the platform is being used (anonymized statistics might be shared if you opt-in).
- Information Typically Requested:
- Organization Name: The name of your company, university, team, or community.
- Organization Type: A category describing your organization (e.g., Education, Software Development, Community, Enterprise, Non-profit).
- Industry: Your organization's primary industry.
- Size: The approximate number of employees or members in your organization.
- Country: The country where your organization is based.
- Website (Optional): Your organization's official website.
Providing accurate information here can be helpful, but some fields might be optional.
Server Registration (Optional but Recommended for Connectivity Services)
Rocket.Chat offers the option to register your self-hosted server with their services. Registration is not mandatory for the core functionality of Rocket.Chat to work, but it unlocks certain "Connectivity Services," which can enhance your experience.
-
Benefits of Registration:
- Push Notifications: Enables mobile push notifications for users on iOS and Android devices if you don't set up your own push notification gateway (which is complex). Rocket.Chat's gateway acts as a proxy.
- Marketplace Access: Easier access to install official apps and integrations from the Rocket.Chat Marketplace.
- OAuth Services: Simplifies setting up OAuth login with providers like Google, GitHub, etc.
- Updates and News: Receive information about new versions and important updates directly within Rocket.Chat.
-
What Registration Entails:
- You agree to Rocket.Chat's Terms of Service and Privacy Policy for these connected services.
- Your server will communicate with Rocket.Chat's infrastructure.
- Some non-sensitive, aggregated usage statistics might be shared to help Rocket.Chat improve its services (you can usually control the level of data shared or opt-out of certain types of telemetry in the admin settings later).
-
Decision:
- If you need push notifications without complex setup: Registration is highly recommended.
- If you want easy access to the official marketplace: Registration is beneficial.
- If you have strict data privacy requirements and want zero external communication: You can choose to "Keep Standalone" or "Register Later." If you choose standalone, features like push notifications via Rocket.Chat's gateway will not work.
You can typically choose between:
- Register with Rocket.Chat Cloud: This creates an account on their cloud portal and links your server.
- Keep Standalone (or Register Later/Skip): Proceeds without registration. You can always register later from the Admin settings.
For most users, especially those wanting a fully-featured experience with mobile app support, registering is a good idea. Ensure you review the terms if you have concerns.
Workspace Configuration
The final step of the wizard usually involves some basic settings for how your workspace will operate.
- Settings Often Configured Here:
- Default Language: The default language for the workspace user interface. Users can often override this in their personal settings.
- Server Type:
- Public Community: For open communities where users might self-register (if enabled).
- Private Team: For internal teams where user accounts are typically created by administrators or through invites. This often sets more restrictive default permissions.
- Allow User Registration: Whether new users can create accounts themselves or if accounts must be created by an admin. For private company/university chats, this is usually disabled. For public communities, it might be enabled.
- Anonymous Read (Sometimes): Whether non-logged-in users can read public channels. Usually disabled for private setups.
These settings can almost always be changed later in the Admin panel under "Workspace" or "General" settings.
After completing these steps, you'll click a "Finish" or "Go to your workspace" button. You will then be taken to the main Rocket.Chat interface, logged in as the administrator you created.
Workshop Completing the Rocket.Chat Setup Wizard
Objective
To walk through the Rocket.Chat Setup Wizard, create the initial administrator account, configure basic organization and workspace settings, and gain access to the main Rocket.Chat interface.
Prerequisites
- Rocket.Chat and MongoDB services running (launched via Docker Compose).
- Rocket.Chat accessible in a web browser via
http://your_server_ip:3000
. - A valid email address for the administrator account.
- Information about your (test or real) organization.
Steps
1. Access Your Rocket.Chat Instance
Open your web browser and navigate to http://your_server_ip:3000
(replace your_server_ip
with your server's public IP address). You should be greeted by the first page of the Rocket.Chat Setup Wizard. It will likely ask for your administrator account details.
2. Create Admin Account
Fill in the fields for the administrator user:
- Full Name: Enter your name (e.g.,
John Doe
,University Admin
). - Username: Choose a username (e.g.,
admin
,johndoe
). This cannot be easily changed later for this first admin, so choose wisely. - Email: Enter your valid email address. This will be used for login and recovery.
- Password: Create a strong password.
- Confirm Password: Re-enter the password.
Click "Continue" or "Next".
3. Organization Info
The next page will ask for details about your organization.
- Organization Name: E.g.,
My University Chat
,Awesome Project Team
. - Organization Type: Select from the dropdown (e.g.,
Education
,Small Business
,Community
). - Industry: Select from the dropdown (e.g.,
Higher Education
,Technology
). - Size: Select the appropriate size range.
- Country: Select your country.
- Website (Optional): Enter your organization's website if applicable.
Click "Continue" or "Next".
4. Server Registration
This page will present the option to register your server with Rocket.Chat Cloud for connectivity services (push notifications, marketplace, etc.) or to keep it standalone.
- Option 1: Register (Recommended for full features)
- If you choose to register, you might be asked to agree to terms and conditions and potentially create a Rocket.Chat Cloud account or log in if you already have one. Follow the on-screen prompts. This usually involves providing your email and confirming it.
- Option 2: Keep Standalone / Register Later / Skip
- If you prefer not to register at this time, look for an option like "Register Later," "Keep Standalone," or "Skip." This will bypass the registration process for now. You can register later from the Admin settings (
Administration
->Workspace
->Registration
).
- If you prefer not to register at this time, look for an option like "Register Later," "Keep Standalone," or "Skip." This will bypass the registration process for now. You can register later from the Admin settings (
Make your choice and proceed. For this workshop, if you are unsure, registering is generally fine and provides more features out-of-the-box. If privacy is paramount and you wish to avoid any external connections, choose standalone.
Click "Continue" or "Next".
5. Workspace Behavior / Settings
The final page usually asks about some default behaviors for your workspace.
- Server Type:
Public Community
: More open, may allow self-registration if enabled.Private Team
: More restricted, user creation typically admin-controlled. For a university or internal team,Private Team
is often more appropriate.
- Allow new user registration by default (or similar wording):
Yes/True
: Anyone with access to the URL can attempt to create an account.No/False
: Only administrators can create new users or invite them. For a private setup, set this toNo/False
.
- Default language: Choose your preferred default language for the workspace.
Review these settings and choose what's appropriate for your intended use case. These can be changed later.
Click "Save Changes", "Finish", or "Go to your workspace".
6. Confirm and Finish
You might see a confirmation page summarizing your choices. Click the final button to enter your workspace.
You should now be redirected to the main Rocket.Chat interface (e.g., http://your_server_ip:3000/home
), logged in as the administrator account you just created. You'll likely see a default channel (e.g., #general
) and a welcome message.
Explore the interface a bit. Click on your avatar (usually top left) to see user options and access Administration settings.
Conclusion
You have successfully completed the Rocket.Chat Setup Wizard. An administrator account has been created, basic organizational details are set, and initial workspace configurations are in place. Your Rocket.Chat server is now ready for further customization and user management. You can now access the main chat interface and the powerful Administration panel to configure your server in more detail.
Basic User Management
After the initial setup, one of the first tasks you'll likely perform as an administrator is managing users. Rocket.Chat provides a comprehensive user management interface within its Administration panel. You can create users manually, invite them via email, assign roles with different permission levels, and manage existing user accounts.
Creating Users Manually
Manually creating users is useful for:
- Adding a small number of initial users.
- Creating service accounts or specific test accounts.
- Situations where users don't have email addresses or cannot self-register (if self-registration is disabled).
Steps to Create a User Manually:
- Access Administration Panel: Click on your avatar/profile picture (usually in the top-left corner) and select "Administration".
- Navigate to Users: In the Administration sidebar (usually on the left), find and click on "Users" under the "Workspace" or "Users" section. This will display a list of existing users.
- Click "New": Look for a "New" button (often a
+
icon or labeled "New User") usually located in the top-right corner of the Users list page. - Fill in User Details: A form will appear asking for the new user's information:
- Name: The user's full name or display name (e.g.,
Alice Wonderland
). - Username: A unique username for the user (e.g.,
alice
,awonderland
). This is what they will use to log in. It typically cannot contain spaces or special characters. - Email: The user's email address. This is important for notifications, password resets, and if you use email verification.
- Password: Set an initial password for the user.
- Require password change: It's good practice to check this box. This will force the user to change their password upon their first login.
- Roles: Assign roles to the user (see "Assigning Roles" below). By default, new users usually get the
user
role. - Verified Email (Optional): You can manually mark the email as verified if needed.
- Join default channels: If checked, the user will automatically be added to channels marked as "default" in your workspace.
- Send welcome email: If checked, and if your email (SMTP) settings are configured, Rocket.Chat will send a welcome email to the user with their login details or a link to set their password.
- Set user as active: Ensure this is checked for the user to be able to log in.
- Other options: Depending on the Rocket.Chat version and configuration, there might be other options like setting a profile picture, time zone, etc.
- Name: The user's full name or display name (e.g.,
- Save User: Click the "Save" button to create the user account.
The newly created user will now appear in the user list. You can then share the login credentials (username and initial password) with the user.
Assigning Roles (Admin, Moderator, User)
Roles in Rocket.Chat define what a user can and cannot do within the workspace. Rocket.Chat comes with several predefined roles, and you can also create custom roles (an intermediate/advanced topic). The primary default roles are:
user
: This is the standard role for most users. Users with this role can:- Send and receive messages in channels they are members of.
- Create public and private channels (by default, this permission can be restricted).
- Manage their own profile settings.
- Participate in direct messages and discussions.
- Cannot access the Administration panel (except for their own profile).
moderator
: This role has elevated privileges within specific channels or globally. Moderators can typically:- Delete messages from other users in channels they moderate.
- Edit messages from other users (permission-dependent).
- Remove users from channels.
- Set channel topics, announcements, and descriptions.
- Manage channel pruning (deleting old messages).
- They do not have full admin access to server settings.
- Moderator privileges are often assigned on a per-channel basis rather than globally, although global moderators are possible.
admin
: The administrator role has full access to all settings and functionalities of the Rocket.Chat workspace. Admins can:- Access the Administration panel.
- Manage users (create, delete, edit, assign roles).
- Configure all workspace settings (permissions, layout, security, integrations, etc.).
- View audit logs.
- Install and manage apps from the marketplace.
- Basically, do anything on the server.
- Use with caution: Grant admin privileges only to trusted individuals who require them.
guest
: A limited role typically used for external users (clients, partners) who need temporary or restricted access to specific channels. Guests cannot usually create channels or see the full user directory.bot
: A special role for bot accounts, which often have specific API permissions and are treated differently in the UI.anonymous
: For users who are not logged in (if anonymous read access is enabled). They have very limited read-only permissions for public channels.livechat-agent
andlivechat-manager
: Roles related to the Live Chat feature (if enabled), used for customer support interactions.
How to Assign/Change Roles:
- Go to
Administration
->Users
. - Find the user whose roles you want to change and click on their username or an "Edit" icon next to their entry.
- In the user's edit screen/profile, look for a "Roles" section (it might be under an "Info" tab or similar).
- You'll see a list of currently assigned roles and an input field or dropdown to add new roles.
- Type the name of the role you want to add (e.g.,
admin
,moderator
) and select it from the suggestions. - To remove a role, click the "x" or delete icon next to the role name.
- Click "Save" to apply the changes.
Important Considerations: * Principle of Least Privilege: Grant users only the roles and permissions they absolutely need to perform their tasks. Avoid giving everyone admin access. * Multiple Roles: Users can have multiple roles. Their effective permissions will be a combination (usually the most permissive) of all assigned roles.
Inviting Users
Inviting users via email is a convenient way to add new members to your workspace, especially if self-registration is disabled. If your SMTP server is configured correctly, Rocket.Chat can send an invitation email containing a unique link that the user can click to create their account and set their password.
Steps to Invite Users:
- Ensure SMTP is Configured (Crucial Prerequisite): For email invitations to work, you must have correctly configured your email settings in
Administration
->Settings
->Email
->SMTP
. Without a working SMTP setup, invitation emails cannot be sent. (SMTP configuration will be covered in the Intermediate section, but it's a prerequisite for this feature). - Access Administration Panel: Click avatar -> "Administration".
- Navigate to Users: Go to "Users".
- Click "Invite": Look for an "Invite" button (often an envelope icon or labeled "Invite User" or "Invite Members").
- Enter Email Addresses: A dialog or form will appear. Enter one or more email addresses of the people you want to invite. You can usually enter multiple addresses separated by commas, semicolons, or on new lines.
- Choose Channels (Optional): You might have an option to automatically add invited users to specific channels once they join.
- Send Invitations: Click the "Send" or "Invite" button.
Rocket.Chat will then generate unique invitation tokens for each email address and send out the invitation emails. The user receives an email, clicks the link, and is guided through setting up their account (choosing a username, password, etc.).
Managing Invitations:
* You can usually see a list of pending invitations in Administration
-> Users
-> Invitations
(or a similar section).
* From there, you might be able to resend invitations or revoke them if needed.
Alternative Invitation Method (Manual Link Sharing):
If SMTP is not configured, or if you prefer a different workflow, some Rocket.Chat setups allow administrators to generate invitation links manually.
- Go to
Administration
->Settings
->User Registration
(orAccounts
). - Look for an option related to "Invitation Link" or "Invite URL." You might be able to generate a link that can be shared.
- This link, when visited, allows a user to sign up. Be careful with how widely you share such a link if it's a general-purpose one, as anyone with the link could potentially register (unless there are other restrictions in place, like email domain whitelisting).
User management is an ongoing task. As your team grows or changes, you'll regularly interact with these features to add new members, adjust roles, and deactivate accounts for users who no longer need access.
Workshop Managing Your First Users
Objective
To practice basic user management tasks in Rocket.Chat: manually creating a new user, assigning different roles, and (conceptually, if SMTP is not yet configured) understanding the user invitation process.
Prerequisites
- A running Rocket.Chat instance, accessible via a web browser.
- Administrator access to the Rocket.Chat instance (logged in as the admin user created during the setup wizard).
- A few dummy email addresses (can be fake for manual creation, but for actual invites they'd need to be real and SMTP configured).
Steps
1. Log in as Admin
Ensure you are logged into your Rocket.Chat instance with the administrator account you created earlier (e.g., admin
).
2. Navigate to User Management
- Click on your avatar/profile picture in the top-left corner.
- Select "Administration" from the dropdown menu.
- In the Administration panel's left sidebar, find and click on "Users" (it might be under a "Workspace" or "Users" category). You should see your own admin account listed.
3. Create a New User Manually
Let's create a standard user account.
- On the Users page, click the "New" button (usually a
+
icon or labeled "New User" in the top-right). - Fill in the user's details:
- Name:
Test User One
- Username:
testuser1
(must be unique, no spaces) - Email:
testuser1@example.com
(this doesn't need to be a real email for manual creation if you don't send a welcome email, but it's good practice to use a valid format) - Password:
Password123!
(choose a temporary password) - Confirm Password:
Password123!
- Require password change: Check this box (recommended).
- Roles: Ensure the
user
role is selected by default. You can typeuser
if it's not there and select it. - Join default channels: Keep this checked.
- Send welcome email: Uncheck this for now, as SMTP might not be configured yet. If it were, checking this would send an email.
- Set user as active: Ensure this is checked.
- Name:
- Click the "Save" button.
You should see Test User One
(or testuser1
) appear in the user list.
4. Explore User Roles and Modify a User's Role
Let's promote testuser1
to have moderator-like capabilities for learning purposes.
- In the user list, find
testuser1
and click on their username (or an "Edit" icon if available) to open their profile/edit page. - Look for the "Roles" section. You should see
user
listed. - In the input field for adding roles, type
moderator
. Selectmoderator
from the list that appears. - Now,
testuser1
should have bothuser
andmoderator
roles. - Click "Save".
Observe the change:
Although testuser1
now has the moderator
role, global moderator capabilities might require specific channel assignments or further permission tweaks depending on your Rocket.Chat version and default permission settings. For now, just note that the role has been added. Later, when managing channels, you could assign this user as a moderator for a specific channel.
Demote the user:
- Go back to
testuser1
's edit page. - In the "Roles" section, click the 'x' next to the
moderator
role to remove it. - Click "Save". The user is now back to just having the
user
role.
5. (Conceptual) Invite a User via Email
We won't send an actual email unless you have already configured SMTP, but let's walk through where you would do it.
- In the Administration panel, go to "Users".
- Click the "Invite" button (often an envelope icon or labeled "Invite User" or similar).
- An "Invite Users" dialog will appear.
- Emails to invite: You would enter one or more valid email addresses here, e.g.,
friend1@example.com
,colleague2@example.org
. - Channels (Optional): You could select channels these invited users should automatically join.
- Emails to invite: You would enter one or more valid email addresses here, e.g.,
- Clicking "Send" would, if SMTP is configured, send invitation emails. If not, it might show an error or do nothing.
- If you try this without SMTP, note any errors. This highlights the dependency.
- Close the invite dialog.
Where to configure SMTP (for future reference):
- In the Administration panel, navigate to
Settings
. - In the Settings search bar, type
SMTP
or find it under theEmail
category. - Here you would enter your SMTP server details (host, port, username, password, security). This will be covered in a later workshop.
6. Verify User Access (Optional Advanced Step)
If you want to test if the testuser1
account works:
- Option A: Incognito/Private Browsing Window
- Open a new incognito or private browsing window in your web browser (this prevents using your admin session's cookies).
- Navigate to
http://your_server_ip:3000
. - Try to log in as
testuser1
with the passwordPassword123!
. - If you checked "Require password change", you should be prompted to set a new password immediately.
- Once logged in, observe that this user does not have an "Administration" option in their profile menu.
- Log out.
- Option B: Impersonate User (If available and enabled)
- Some Rocket.Chat versions allow admins to impersonate other users for troubleshooting.
- Go to
Administration
->Users
. - Find
testuser1
. There might be an "Impersonate" action (e.g., under a three-dot menu). - If you impersonate, you'll see Rocket.Chat as
testuser1
would. Remember to "Stop Impersonating" when done. This feature might need to be enabled in settings (Accounts
->Allow User Impersonation
).
7. Deactivate or Delete a User (Use with Caution)
Let's say testuser1
no longer needs access.
- Deactivating a User:
- Go to
testuser1
's edit page (Administration
->Users
-> clicktestuser1
). - Uncheck the "Set user as active" box (or look for an "Active" toggle and switch it off).
- Click "Save".
- The user
testuser1
will no longer be able to log in, but their account and messages remain in the system. This is often preferred over deletion for auditing purposes.
- Go to
- Deleting a User (Irreversible):
- Go to
testuser1
's edit page. - Look for a "Delete" button or option (often under a "Danger Zone" or three-dot menu).
- You will likely be asked to confirm deletion, and you might have options regarding what to do with their messages (e.g., delete them or retain them under a generic user).
- Be very careful with user deletion, as it's usually permanent. For this workshop, you can proceed with deleting
testuser1
if you wish, as it's just a test account.
- Go to
Conclusion
In this workshop, you practiced fundamental user management tasks: creating a user manually, modifying user roles, and understanding the process for inviting users. You also briefly explored how to test user access and the difference between deactivating and deleting users. These skills are essential for maintaining any multi-user application, including your Rocket.Chat server. As you progress, you'll encounter more advanced user management features like Single Sign-On (SSO) and LDAP integration.
2. Intermediate Configuration and Management
With your Rocket.Chat server installed and basic user management understood, it's time to delve into intermediate configurations. This section focuses on securing your instance, customizing its appearance and behavior, managing communication effectively, and starting to explore integrations. These steps are crucial for moving from a basic setup to a more robust, user-friendly, and production-ready communication platform.
Securing Your Rocket.Chat Instance
Security should be a top priority for any self-hosted service, especially one that handles potentially sensitive communications. The default setup (HTTP on port 3000) is fine for initial testing but is not secure for real-world use. We'll cover three key areas: implementing HTTPS using a reverse proxy, configuring a host-based firewall, and enabling two-factor authentication.
Implementing HTTPS with a Reverse Proxy (Nginx/Apache/Caddy)
Currently, your Rocket.Chat instance is accessible via http://your_server_ip:3000
. This means all communication between users' browsers and your server is unencrypted and can be intercepted. To secure this, you need to implement HTTPS (HTTP Secure), which encrypts the traffic using SSL/TLS certificates.
The recommended way to enable HTTPS for a Dockerized application like Rocket.Chat is to use a reverse proxy.
Understanding Reverse Proxies
A reverse proxy is a server that sits in front of one or more web servers (in our case, the Rocket.Chat container) and forwards client requests (from web browsers) to those web servers.
Benefits of using a reverse proxy for Rocket.Chat:
- SSL/TLS Termination: The reverse proxy can handle the encryption and decryption of HTTPS traffic. This offloads the SSL/TLS processing from the Rocket.Chat application itself, simplifying its configuration and potentially improving performance. You install SSL certificates on the reverse proxy.
- Load Balancing (Advanced): If you scale Rocket.Chat to run multiple instances, a reverse proxy can distribute traffic among them, improving performance and availability.
- Caching: The reverse proxy can cache static content (images, CSS, JavaScript files), reducing the load on the Rocket.Chat server and speeding up load times for users.
- Security: It can provide an additional layer of security by hiding the internal structure of your network, filtering malicious requests (e.g., with a Web Application Firewall - WAF module), and implementing rate limiting.
- Serving Multiple Applications on One Server/IP: You can use a single reverse proxy to serve multiple websites or applications from the same server, each with its own domain name, all using the standard HTTP (80) and HTTPS (443) ports. For example,
chat.yourdomain.com
could go to Rocket.Chat, andblog.yourdomain.com
could go to a WordPress site, both managed by the same reverse proxy. - WebSocket Support: Rocket.Chat relies heavily on WebSockets for real-time communication. Reverse proxies like Nginx, Apache, and Caddy can be configured to correctly proxy WebSocket connections.
- Custom Headers and URL Rewrites: Allows for advanced manipulation of requests and responses.
Popular Reverse Proxy Choices:
- Nginx (Engine-Ex): Extremely popular, high-performance, lightweight, and feature-rich. Excellent for SSL/TLS termination, load balancing, and serving static content. Extensive documentation and community support. This is often the preferred choice for Dockerized applications.
- Apache HTTP Server: Another very popular, robust, and flexible web server that can also function as a reverse proxy (using modules like
mod_proxy
). It's known for its.htaccess
file configuration flexibility (though this is less relevant when used purely as a reverse proxy). - Caddy: A modern web server with automatic HTTPS built-in (it can obtain and renew SSL/TLS certificates from Let's Encrypt automatically by default). Known for its simple configuration file format. It's gaining popularity rapidly.
- Traefik: A modern reverse proxy and load balancer designed specifically for microservices and Docker environments. It can automatically discover services and configure routes, often integrating directly with Docker's API. Steeper learning curve for some, but very powerful for dynamic environments.
For this guide, we will focus on using Nginx due to its widespread adoption, excellent performance, and robust capabilities for handling Rocket.Chat's specific needs (like WebSockets). The principles, however, are similar for other reverse proxies.
Setting Up Nginx as a Reverse Proxy
The general process involves:
- Install Nginx: Install the Nginx web server on your host system (not inside a Docker container, though it could be, for simplicity we'll install it directly on the host).
- Configure Nginx: Create a server block (virtual host) configuration file for your Rocket.Chat domain. This configuration will tell Nginx:
- To listen on port 80 (for HTTP) and port 443 (for HTTPS).
- The domain name to respond to (e.g.,
chat.yourdomain.com
). - Where to find the SSL/TLS certificate files.
- To proxy requests for that domain to the Rocket.Chat application running on
http://localhost:3000
(orhttp://127.0.0.1:3000
). - To correctly handle WebSocket connections.
- To redirect HTTP traffic to HTTPS.
- Obtain SSL/TLS Certificates: Use a tool like Certbot with Let's Encrypt to get free, trusted SSL/TLS certificates.
- Update Rocket.Chat
ROOT_URL
: Change theROOT_URL
environment variable in yourdocker-compose.yml
file to reflect your new HTTPS domain (e.g.,https://chat.yourdomain.com
) and restart Rocket.Chat.
Obtaining SSL/TLS Certificates with Let's Encrypt (Certbot)
Let's Encrypt is a free, automated, and open Certificate Authority (CA) that provides digital certificates to enable HTTPS on websites. Certbot is a client software that automates the process of obtaining and renewing Let's Encrypt certificates and configuring web servers to use them.
How Certbot Works (typically with Nginx/Apache):
- Installation: You install Certbot and its appropriate plugin for your web server (e.g.,
python3-certbot-nginx
). - Domain Validation: To issue a certificate, Let's Encrypt needs to verify that you control the domain name. Certbot handles this automatically using different "challenges":
- HTTP-01 Challenge: Certbot places a specific file in a specific location on your web server (
/.well-known/acme-challenge/
). Let's Encrypt's servers then try to download this file via HTTP. If successful, it proves you control the domain. This requires your domain to be pointing to your server's IP and port 80 to be open. - DNS-01 Challenge: Certbot asks you to place a specific TXT record in your domain's DNS settings. Let's Encrypt's servers then query DNS for this record. This method doesn't require your server to be accessible from the internet on port 80 and can be used for wildcard certificates (e.g.,
*.yourdomain.com
), but it often requires API access to your DNS provider for automation.
- HTTP-01 Challenge: Certbot places a specific file in a specific location on your web server (
- Certificate Issuance: Once validation is successful, Let's Encrypt issues the certificate. Certbot downloads it and typically places the certificate files in
/etc/letsencrypt/live/your_domain.com/
.fullchain.pem
: Your server's certificate plus all intermediate certificates. This is what Nginx usually needs forssl_certificate
.privkey.pem
: Your certificate's private key. This is what Nginx usually needs forssl_certificate_key
.
- Web Server Configuration: Certbot can automatically configure your Nginx or Apache server block to use the newly obtained certificate and set up HTTPS redirection.
- Automatic Renewal: Let's Encrypt certificates are valid for 90 days. Certbot sets up a cron job or systemd timer that automatically renews the certificates before they expire.
Using Certbot and Let's Encrypt is the standard way to get free and trusted SSL/TLS certificates for most self-hosted projects.
Workshop Securing Rocket.Chat with Nginx and Let's Encrypt
Objective
To secure your Rocket.Chat instance by setting up Nginx as a reverse proxy, obtaining a free SSL/TLS certificate from Let's Encrypt using Certbot, configuring Nginx to use HTTPS, and updating Rocket.Chat's ROOT_URL
.
Prerequisites
- A running Rocket.Chat instance accessible via
http://your_server_ip:3000
(from previous workshops). - A registered domain name (e.g.,
chat.yourdomain.com
) that you control. - DNS
A
record for your chosen domain/subdomain pointing to your server's public IP address. You can check if it has propagated usingping chat.yourdomain.com
ornslookup chat.yourdomain.com
from your local machine or another server. Propagation can take some time (minutes to hours). - Server running Ubuntu/Debian with
sudo
access. - Docker and Docker Compose installed, with Rocket.Chat running in Docker.
- Ports 80 (HTTP) and 443 (HTTPS) must be open on your server's firewall and accessible from the internet. If
ufw
is active:
Scenario
- Your Domain: Let's assume your domain is
chat.example.com
. Replacechat.example.com
with your actual domain name throughout this workshop. - Rocket.Chat internal address:
http://localhost:3000
(as per ourdocker-compose.yml
).
Steps
Part 1 Installing Nginx
-
Update Package List:
-
Install Nginx:
-
Verify Nginx Installation: Start Nginx if it's not already running and enable it to start on boot:
Check its status: You should seeactive (running)
. Open your web browser and navigate tohttp://your_server_ip
. You should see the default Nginx welcome page ("Welcome to nginx!"). This confirms Nginx is working and serving content on port 80.
Part 2 Configuring Nginx as a Reverse Proxy for Rocket.Chat
We need to create an Nginx server block configuration file for your Rocket.Chat domain.
-
Create Nginx Configuration File: Nginx configurations for sites are typically stored in
Paste the following configuration into the file. Remember to replace/etc/nginx/sites-available/
and then symlinked to/etc/nginx/sites-enabled/
.chat.example.com
with your actual domain name.# Upstream server for Rocket.Chat (running on localhost:3000) upstream rocketchat_server { server 127.0.0.1:3000; } # Server block for HTTP (will redirect to HTTPS) server { listen 80; listen [::]:80; server_name chat.example.com; # Replace with your domain # For Let's Encrypt ACME challenge (HTTP-01) location /.well-known/acme-challenge/ { root /var/www/html; allow all; } location / { return 301 https://$host$request_uri; # Redirect all HTTP to HTTPS } } # Server block for HTTPS server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name chat.example.com; # Replace with your domain # SSL Configuration - Paths will be updated by Certbot later # For now, these are placeholders or commented out. # ssl_certificate /etc/letsencrypt/live/chat.example.com/fullchain.pem; # ssl_certificate_key /etc/letsencrypt/live/chat.example.com/privkey.pem; # include /etc/letsencrypt/options-ssl-nginx.conf; # Recommended SSL parameters # ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # Diffie-Hellman parameters # Security Headers (Optional but Recommended) # add_header X-Frame-Options "SAMEORIGIN" always; # add_header X-XSS-Protection "1; mode=block" always; # add_header X-Content-Type-Options "nosniff" always; # add_header Referrer-Policy "no-referrer-when-downgrade" always; # add_header Content-Security-Policy "frame-ancestors 'self'" always; # Adjust as needed for integrations # add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; # Client Body Size (adjust if you need larger file uploads through Nginx) client_max_body_size 100M; # Example: 100 MB # Logging access_log /var/log/nginx/rocketchat.access.log; error_log /var/log/nginx/rocketchat.error.log; location / { proxy_pass http://rocketchat_server; # Pass requests to the upstream proxy_http_version 1.1; # Headers required for Rocket.Chat proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; # Pass the original host header proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; # To support long-lived connections for WebSockets proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; # For Rocket.Chat 3.x.x+, set this to 300s if you experience issues # Or match with Administration -> General -> Idle Timeout Duration (seconds) proxy_buffering off; # Recommended for real-time applications } }
Explanation of the Nginx configuration: *
upstream rocketchat_server
: Defines a group of servers. Here, it's just our local Rocket.Chat instance running on port 3000. Using an upstream block makes it easier to add more Rocket.Chat instances later for load balancing. * HTTP Server Block (listen 80
): * Listens on port 80 forchat.example.com
. * Thelocation /.well-known/acme-challenge/
block is crucial for Certbot's HTTP-01 challenge. It tells Nginx to serve files from/var/www/html
for requests to this path, allowing Let's Encrypt to verify domain ownership. *location / { return 301 https://$host$request_uri; }
: Redirects all other HTTP traffic to the corresponding HTTPS URL. * HTTPS Server Block (listen 443 ssl http2
): * Listens on port 443 forchat.example.com
, enables SSL, and HTTP/2 for better performance. *ssl_certificate
andssl_certificate_key
lines are commented out initially. Certbot will manage these. *client_max_body_size 100M;
: Sets the maximum allowed size of the client request body. This affects file uploads. Adjust it to match or exceed Rocket.Chat's file upload limit settings if you don't want Nginx to block larger uploads. *access_log
anderror_log
: Define custom log files for this site. *location / { ... }
: This block handles all requests to your domain. *proxy_pass http://rocketchat_server;
: Forwards the request to therocketchat_server
upstream (i.e.,http://127.0.0.1:3000
). *proxy_http_version 1.1;
: Uses HTTP/1.1 for proxied connections. *proxy_set_header Upgrade $http_upgrade;
andproxy_set_header Connection "upgrade";
: These headers are essential for WebSocket connections to work correctly. Rocket.Chat uses WebSockets extensively for real-time updates. *proxy_set_header Host $host;
: Passes the original host header from the client to Rocket.Chat. This is important for Rocket.Chat to know which domain it's being accessed from, especially if you use virtual hosts. *X-Real-IP
,X-Forwarded-For
,X-Forwarded-Proto
: These headers pass information about the original client request (IP address, protocol) to Rocket.Chat, which is useful for logging and for Rocket.Chat to determine if the original connection was HTTPS. *proxy_connect/send/read_timeout
: Adjust these timeouts if needed. Longerproxy_read_timeout
can prevent premature disconnection of WebSocket connections. *proxy_buffering off;
: Disables buffering of responses from the proxied server. This is often recommended for applications with real-time, long-lived connections like chat services, as it can improve responsiveness. -
Create a Directory for Let's Encrypt Challenges (if it doesn't exist): The Nginx config refers to
/var/www/html
for Let's Encrypt challenges. This directory is usually present, but ensure it exists and Nginx can write to it (or Certbot can). -
Enable the Nginx Configuration: Create a symbolic link from
It's good practice to remove the default Nginx welcome page configuration if it's enabled, to avoid conflicts, especially if your server IP is also what your domain points to.sites-available
tosites-enabled
: -
Test Nginx Configuration: Before restarting Nginx, always test your configuration for syntax errors:
If you seenginx: configuration file /etc/nginx/nginx.conf test is successful
, you're good. If there are errors,nano /etc/nginx/sites-available/rocketchat
again and fix them. Common errors include typos or missing semicolons. -
Reload Nginx: If the test is successful, reload Nginx to apply the new configuration:
At this point, if you navigate to http://chat.example.com
(using your domain), you should be redirected to https://chat.example.com
. However, because we haven't installed SSL certificates yet, your browser will show a security warning (e.g., "Your connection is not private"). This is expected.
Part 3 Installing Certbot and Obtaining SSL Certificates
-
Install Certbot and the Nginx Plugin: Certbot recommends installing via Snap for the latest version, but using
apt
is also common. We'll useapt
here as it's often simpler if Snap isn't already in use.certbot
: The main Certbot client.python3-certbot-nginx
: The Nginx plugin for Certbot, which allows Certbot to automatically configure Nginx for SSL.
-
Obtain the SSL Certificate: Run Certbot, telling it to use the Nginx plugin and specifying your domain name.
sudo certbot
: Runs Certbot with superuser privileges.--nginx
: Specifies that you are using the Nginx plugin. Certbot will attempt to detect your Nginx configuration and modify it automatically.-d chat.example.com
: Specifies the domain name for which you want to obtain a certificate. Replacechat.example.com
with your actual domain. If you have multiple domains pointing to this server block (e.g.,www.chat.example.com
), you can add them with additional-d
flags:sudo certbot --nginx -d chat.example.com -d www.chat.example.com
.
Certbot will guide you through a few prompts: * Email Address: Enter your email address. This is used for urgent renewal notices and security updates. * Terms of Service: You'll need to agree to the Let's Encrypt Terms of Service. * Mailing List (Optional): You can choose whether to share your email address with the Electronic Frontier Foundation (EFF), a founding partner of Let's Encrypt. * HTTP to HTTPS Redirection: Certbot will ask if you want to redirect HTTP traffic to HTTPS.
Choose option 2 (Redirect). This will ensure all traffic to your site uses HTTPS. Our Nginx config already has a redirect, but letting Certbot manage this is fine and ensures it's correctly configured for SSL.Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
If everything is successful, Certbot will obtain the certificate, install it, and configure Nginx to use it. You should see a message like:
Certbot will also tell you where your certificate and key are stored (typicallySuccessfully deployed certificate for chat.example.com to /etc/nginx/sites-enabled/rocketchat Congratulations! You have successfully enabled HTTPS on https://chat.example.com
/etc/letsencrypt/live/chat.example.com/fullchain.pem
andprivkey.pem
). It also mentions that your certificate will expire on a certain date and how to test automatic renewal. -
Verify Nginx Configuration After Certbot: Certbot modifies your Nginx configuration file (
You should see that Certbot has added lines similar to these in your/etc/nginx/sites-available/rocketchat
). Let's examine the changes.server { listen 443 ssl ... }
block:Certbot also typically comments out or modifies the existing SSL lines and ensures the HTTP to HTTPS redirect is correctly set up.ssl_certificate /etc/letsencrypt/live/chat.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/chat.example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
-
Test HTTPS Access: Open your web browser and navigate to
https://chat.example.com
(using your domain).- You should see the Rocket.Chat setup wizard or login page.
- Your browser should show a padlock icon in the address bar, indicating a secure HTTPS connection. Click on it to view certificate details.
- If you try accessing
http://chat.example.com
, you should be automatically redirected tohttps://chat.example.com
.
Part 4 Automating Certificate Renewal
Let's Encrypt certificates are valid for 90 days. Certbot automatically sets up a mechanism (usually a systemd timer or a cron job) to renew them before they expire.
-
Test Automatic Renewal: You can perform a "dry run" to simulate the renewal process without actually renewing the certificate:
If the dry run is successful, it means automatic renewal should work. You'll see a message like:No further action is typically needed for renewal. Certbot's package usually installs a systemd timer (Congratulations, all simulated renewals succeeded: /etc/letsencrypt/live/chat.example.com/fullchain.pem (success)
certbot.timer
) or a cron job that runscertbot renew
twice a day. This command checks all certificates managed by Certbot and renews any that are due for renewal (typically within 30 days of expiry). When a certificate is renewed, Certbot will also automatically reload Nginx to pick up the new certificate.You can check the status of the systemd timer (if used):
Part 5 Updating Docker Compose and Rocket.Chat ROOT_URL
Now that Nginx is handling HTTPS and proxying requests to Rocket.Chat, you need to tell Rocket.Chat its correct public URL.
-
Stop Rocket.Chat Services: Navigate to your Rocket.Chat project directory:
-
Edit
Find thedocker-compose.yml
:environment
section for therocketchat
service and update theROOT_URL
:Crucially, change# ... other rocketchat service settings ... environment: - PORT=3000 - ROOT_URL=https://chat.example.com # Change this line! - MONGO_URL=mongodb://mongo:27017/rocketchat?replicaSet=rs0 - MONGO_OPLOG_URL=mongodb://mongo:27017/local?replicaSet=rs0 # - MAIL_URL=smtp://user:pass@smtp.example.com:587/ # ... rest of the file ...
ROOT_URL
fromhttp://localhost:3000
(or whatever it was) tohttps://chat.example.com
(using your actual HTTPS domain). This is very important for Rocket.Chat to generate correct links, serve assets properly, and for features like OAuth and integrations to work. -
Restart Rocket.Chat Services:
Wait a minute or two for Rocket.Chat to start. You can monitor logs withsudo docker compose logs -f rocketchat
. -
Test Again: Go to
https://chat.example.com
in your browser. Everything should now work correctly over HTTPS, with all assets loading properly. If you had already completed the setup wizard, you should see your Rocket.Chat workspace. If not, the wizard will appear.Optional Security Headers in Nginx (Recommended): Uncomment and customize the security headers in your
/etc/nginx/sites-available/rocketchat
file within theserver { listen 443 ssl ... }
block:*# Security Headers (Optional but Recommended) add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; # For Content-Security-Policy, start with a restrictive policy and loosen as needed. # Rocket.Chat may require 'unsafe-inline' and 'unsafe-eval' for some scripts or styles # if custom CSS/JS is used or for certain features. Check browser console for errors. # A basic CSP that might work (test thoroughly): # add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data:; font-src 'self' https://fonts.gstatic.com; object-src 'none'; frame-ancestors 'self';" always; # For Rocket.Chat, especially if you use integrations that embed content (like Jitsi), frame-ancestors might need adjustment. # If you use the "Embed" feature (Administration -> Layout -> User Interface -> Embed) to embed Rocket.Chat elsewhere, # you'll need to adjust frame-ancestors accordingly, e.g., frame-ancestors 'self' https://your-other-domain.com; add_header Content-Security-Policy "frame-ancestors 'self';" always; # Start with this and adjust if needed for embeds. add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; # HSTS header
X-Frame-Options
: Prevents clickjacking attacks by controlling whether your site can be embedded in an<iframe>
.SAMEORIGIN
allows embedding only from your own domain. *X-XSS-Protection
: Enables the browser's built-in Cross-Site Scripting (XSS) filter.1; mode=block
prevents rendering the page if an XSS attack is detected. *X-Content-Type-Options
: Prevents browsers from MIME-sniffing the content type, reducing risk of attacks that leverage content type confusion.nosniff
is the recommended value. *Referrer-Policy
: Controls how much referrer information is sent with requests.no-referrer-when-downgrade
prevents sending the referrer header when navigating from HTTPS to HTTP. *Content-Security-Policy (CSP)
: A powerful header to prevent XSS and data injection attacks by specifying which sources of content (scripts, styles, images, etc.) are allowed. CSP can be complex to configure correctly, especially for feature-rich applications like Rocket.Chat. Start with a restrictive policy and gradually loosen it based on browser console errors if features break.frame-ancestors 'self'
is a good start for preventing embedding unless you need it. *Strict-Transport-Security (HSTS)
: Tells browsers to always connect to your site using HTTPS for a specified period (max-age).includeSubDomains
applies HSTS to all subdomains.preload
allows you to submit your domain to HSTS preload lists maintained by browser vendors, ensuring browsers never connect via HTTP even on the first visit. Usepreload
with caution: once preloaded, removing your site is a lengthy process. Ensure HTTPS is working perfectly across your entire domain and all subdomains before considering preload.After adding/uncommenting these headers, save the file, test the Nginx configuration (
sudo nginx -t
), and reload Nginx (sudo systemctl reload nginx
). You can test your site's security headers using online tools likesecurityheaders.com
.
Conclusion
You have successfully configured Nginx as a reverse proxy for your Dockerized Rocket.Chat instance, secured it with a free Let's Encrypt SSL/TLS certificate using Certbot, and ensured that Rocket.Chat is aware of its correct HTTPS ROOT_URL
. Your communication is now encrypted between clients and your server. You also learned about automatic certificate renewal and optional security headers to further harden your setup. This is a major step towards a production-ready and secure Rocket.Chat deployment.
Configuring Firewalls (ufw)
A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It acts as a barrier between your trusted internal network (or your server itself) and untrusted external networks (like the internet). Configuring a firewall is a fundamental security measure for any server.
Uncomplicated Firewall (ufw) is a user-friendly front-end for managing iptables
, the default firewall utility in Linux. ufw
aims to simplify the process of configuring a firewall, making it accessible even to those who are not iptables
experts.
Why use a firewall for your Rocket.Chat server?
- Restrict Access: By default, a server might have many network ports open. A firewall allows you to explicitly define which ports should be accessible and from where. For Rocket.Chat, you typically only need to allow traffic on ports for SSH (usually 22), HTTP (80), and HTTPS (43). All other ports can and should be blocked unless explicitly needed by another service.
- Protect Against Unwanted Scans and Attacks: Automated bots and malicious actors constantly scan the internet for servers with open, vulnerable ports. A firewall can drop or reject connections to unneeded ports, reducing your server's attack surface.
- Control Outgoing Connections (Less Common for Basic Setups): While primarily used for incoming traffic, firewalls can also control outgoing connections, preventing compromised software on your server from connecting to malicious external servers.
Basic Principles with ufw
:
- Default Policies: You set default policies for incoming and outgoing traffic. A common security practice is to deny all incoming traffic by default and allow all outgoing traffic by default.
sudo ufw default deny incoming
sudo ufw default allow outgoing
- Allow Specific Services/Ports: You then explicitly allow traffic for services you need (e.g., SSH, HTTP, HTTPS).
sudo ufw allow ssh
(orsudo ufw allow 22/tcp
)sudo ufw allow http
(orsudo ufw allow 80/tcp
)sudo ufw allow https
(orsudo ufw allow 443/tcp
)
- Enable
ufw
: Once your rules are set, you enable the firewall.sudo ufw enable
- Check Status: You can always check the status and current rules.
sudo ufw status verbose
Important Note on SSH:
Before enabling ufw
with a default deny policy, ALWAYS ensure you have an allow rule for SSH. If you don't, you could lock yourself out of your server.
ufw
integrates with application profiles stored in /etc/ufw/applications.d/
. When you install services like Nginx or OpenSSH, they often provide these profiles, allowing you to use commands like sudo ufw allow 'Nginx Full'
(which allows both HTTP and HTTPS) or sudo ufw allow OpenSSH
.
Since our Rocket.Chat application is running inside Docker and exposed via Nginx, we only need to ensure that the ports Nginx listens on (80 for HTTP, 443 for HTTPS) and the SSH port are open on the host firewall. Docker manages its own networking and iptables
rules for container communication, which usually work fine alongside ufw
. However, there can be interactions, especially if Docker's iptables
rules bypass ufw
rules. For most basic setups, allowing the Nginx ports through ufw
is sufficient.
Workshop Basic Firewall Setup with ufw
Objective
To install and configure ufw
(Uncomplicated Firewall) on your Rocket.Chat server to allow only necessary traffic (SSH, HTTP, HTTPS) and block all other incoming connections, enhancing server security.
Prerequisites
- A server running Ubuntu/Debian with
sudo
access. - Nginx installed and configured to serve Rocket.Chat on ports 80 and 443 (from the previous workshop).
- SSH access to your server. Be very careful not to lock yourself out during this workshop.
Steps
1. Install ufw (if not already installed)
ufw
is usually installed by default on Ubuntu, but it might not be on a minimal Debian installation.
2. Check ufw Status
Before making changes, check if ufw
is active and what its current rules are:
Status: inactive
.
3. Set Default Policies A secure approach is to deny all incoming connections by default and allow all outgoing connections. * Deny incoming traffic by default:
This means any traffic not matching an explicit allow rule will be dropped. * Allow outgoing traffic by default: This allows your server to make connections to the outside world (e.g., for system updates, Docker image downloads, or if Rocket.Chat needs to connect to external services).4. Allow Essential Ports
-
Allow SSH (Critically Important!): You MUST allow SSH traffic before enabling the firewall, or you will be locked out. You can allow it by port number (default is 22) or by service name if an application profile exists.
or, if you use a custom SSH port (e.g., 2222): If you are unsure,sudo ufw allow 22/tcp
is safe for the default port. -
Allow HTTP and HTTPS for Nginx: Nginx usually registers application profiles with
You should see entries like:ufw
upon installation. You can list available application profiles:Nginx HTTP
: Allows traffic on port 80.Nginx HTTPS
: Allows traffic on port 443.Nginx Full
: Allows traffic on both ports 80 and 443.OpenSSH
: Allows traffic on port 22.
We will allow
Alternatively, you could add rules by port number: Using the application profile is generally cleaner if available.Nginx Full
as our Nginx setup uses both HTTP (for redirection and Let's Encrypt renewal) and HTTPS.
5. (Optional) Allow Specific Port for Rocket.Chat Direct Access (If Not Using Reverse Proxy Yet) If, for some reason, you are not yet using Nginx and are still accessing Rocket.Chat directly on port 3000 (e.g., during initial testing before setting up Nginx), you would need to allow that port too:
Since we configured Nginx in the previous workshop, this rule for port 3000 should NOT be added if Nginx is your public entry point. Nginx listens on 80/443 and communicates with Rocket.Chat on port 3000 locally (127.0.0.1:3000). This local communication does not need to be exposed through the host's public firewall if Nginx is doing its job. Exposing port 3000 directly would bypass Nginx and your HTTPS setup.6. Enable ufw
After setting your default policies and allowing necessary services/ports, enable ufw
.
Double-check that you have an SSH allow rule before running this command!
ufw
will warn you that enabling it may disrupt existing SSH connections. Type y
and press Enter to proceed.
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
7. Check ufw Status Again Now, check the status to see your active rules:
You should see output similar to this (port numbers or service names might vary slightly based on your choices):Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp ALLOW IN Anywhere # (OpenSSH)
80,443/tcp ALLOW IN Anywhere # (Nginx Full)
22/tcp (v6) ALLOW IN Anywhere (v6) # (OpenSSH)
80,443/tcp (v6) ALLOW IN Anywhere (v6) # (Nginx Full)
8. Test Your Services
* SSH: Ensure your current SSH session is still active. Try opening a new SSH session to your server. If you can connect, your SSH rule is working.
* Rocket.Chat: Open your web browser and navigate to https://chat.example.com
(your domain). Your Rocket.Chat instance should load correctly. If it doesn't, double-check that ports 80 and 443 are allowed and that Nginx is running.
9. (Optional) Rate Limiting SSH (Protection against Brute-Force Attacks)
A common attack vector is brute-forcing SSH passwords. ufw
can help mitigate this by rate-limiting connections to the SSH port. This rule allows a certain number of connection attempts within a time window; further attempts from the same IP are blocked temporarily.
sudo ufw status
again, you might see LIMIT IN
instead of ALLOW IN
for SSH. The default limit is typically 6 connections from the same IP address within 30 seconds.
Managing ufw Rules:
* Deleting a rule:
You can delete rules by number (get numbers with sudo ufw status numbered
) or by specification.
sudo ufw status numbered
# Example output:
# Status: active
# To Action From
# -- ------ ----
# [ 1] 22/tcp LIMIT IN Anywhere
# [ 2] 80,443/tcp ALLOW IN Anywhere
# ...
Conclusion
You have successfully configured ufw
on your server, establishing a basic but effective firewall. By setting default policies to deny incoming traffic and explicitly allowing only SSH, HTTP (for Nginx/Let's Encrypt), and HTTPS (for Nginx), you have significantly reduced your server's attack surface. You also learned how to optionally implement rate limiting for SSH to protect against brute-force attacks. Regularly reviewing and maintaining your firewall rules is an important aspect of server security.
Two-Factor Authentication (2FA)
Two-Factor Authentication (2FA), also known as Multi-Factor Authentication (MFA), adds an extra layer of security to user accounts beyond just a username and password. With 2FA enabled, users are required to provide two different types of verification before gaining access:
- Something they know: Their password.
- Something they have: A code generated by an authenticator app on their smartphone (like Google Authenticator, Authy, FreeOTP), a hardware security key (like a YubiKey), or a code sent via SMS/email (though app-based OTP is generally more secure than SMS/email).
Rocket.Chat supports Time-based One-Time Passwords (TOTP) using authenticator apps, which is a common and secure 2FA method. It can also support 2FA via Email.
Why is 2FA important?
- Protection against compromised passwords: If a user's password is stolen, guessed, or leaked in a data breach, 2FA prevents unauthorized access because the attacker would still need the second factor (the code from the authenticator app).
- Enhanced account security: Significantly reduces the risk of account takeovers.
Enabling 2FA in Rocket.Chat involves two parts:
- Administrator Configuration: The administrator enables and configures 2FA options for the workspace.
- User Enrollment: Each user individually enables 2FA for their own account and pairs it with their chosen authenticator app.
Enabling and Configuring 2FA
Administrators can manage 2FA settings globally for the workspace.
-
Navigate to 2FA Settings:
- Log in to Rocket.Chat as an administrator.
- Go to
Administration
->Settings
. - In the Settings search bar, type "Two Factor" or navigate to the
Accounts
->Two Factor Authentication
section.
-
Configure 2FA Options: You'll find several settings:
- Enable Two Factor Authentication: This is the main switch to turn 2FA on or off for the workspace. Set this to
True
(or toggle it on). - Allow users to enable Two Factor Authentication via:
- TOTP: (Recommended) Allows users to use Time-based One-Time Password apps. This should be enabled.
- Email: Allows users to receive their 2FA codes via email. This is less secure than TOTP (as email accounts can be compromised) but can be an alternative if users don't have smartphones or prefer email. Consider the security implications before enabling this.
- Enforce Two Factor Authentication for users with role(s): (Optional but powerful) This allows administrators to require 2FA for users who have specific roles (e.g.,
admin
,moderator
). If a user with one of these roles has not enabled 2FA, they might be forced to set it up at their next login or lose access to certain features until they do. This is highly recommended for administrator accounts. You can select multiple roles. - Max Delta (TOTP): Defines how many previous or future TOTP codes are considered valid. This accounts for slight clock drifts between the server and the user's device. The default is usually 1 (meaning the current code, one previous, and one future code are accepted). Increasing this slightly (e.g., to 2) can reduce login issues due to clock sync problems but slightly weakens security.
- Trusted Devices (Bypass 2FA): Some systems allow users to mark a device as "trusted" for a certain period (e.g., 30 days), bypassing the 2FA prompt on that device. Rocket.Chat's core 2FA implementation might have this or rely on session management. Check the specific options available in your version.
- Enable Two Factor Authentication: This is the main switch to turn 2FA on or off for the workspace. Set this to
-
Save Changes: After configuring the settings, click the "Save changes" button.
User Enrollment
Once the administrator has enabled 2FA in the workspace settings (specifically TOTP), individual users can enable it for their own accounts.
-
User Navigates to Profile:
- The user logs into their Rocket.Chat account.
- They click on their avatar/profile picture (top-left).
- They select "My Account" or "Profile".
-
Access Security Settings:
- Within their account settings, they look for a "Security" tab or section.
-
Enable Two-Factor Authentication (TOTP):
- There should be an option to "Enable Two-Factor Authentication" or similar, often with a button to "Enable TOTP".
- Clicking this will typically:
- Display a QR code and a secret key (text string).
- Prompt the user to enter their current password for verification.
- Provide an input field for the user to enter a TOTP code from their authenticator app to confirm setup.
-
Set Up Authenticator App:
- The user needs an authenticator app on their smartphone (e.g., Google Authenticator, Authy, Microsoft Authenticator, FreeOTP, 1Password, Bitwarden).
- In the authenticator app, they choose to add a new account.
- They can either scan the QR code displayed by Rocket.Chat using their phone's camera or manually enter the secret key provided.
- The authenticator app will then start generating 6-digit codes that change every 30 seconds for their Rocket.Chat account.
-
Verify and Activate:
- Back in Rocket.Chat, after setting up the authenticator app, the user enters their current password (if prompted).
- Then, they enter the 6-digit code currently displayed in their authenticator app into the "Verification Code" or "Authentication Code" field in Rocket.Chat.
- They click "Verify" or "Enable".
-
Backup Codes (Important!):
- Upon successful activation of TOTP, Rocket.Chat should provide the user with a set of one-time backup codes.
- These codes are extremely important. If the user loses access to their authenticator app (e.g., phone lost, stolen, or reset), these backup codes are the only way they can regain access to their account (unless an admin disables 2FA for them).
- Users should save these backup codes in a very secure place, separate from their password and their primary authenticator device (e.g., print them out and store them safely, save them in a secure password manager). Each backup code can only be used once.
What happens on next login: * The user enters their username and password as usual. * If correct, they will be prompted to enter a 2FA code from their authenticator app. * If they cannot provide a code from the app, they should have an option to use one of their backup codes.
Administrator Intervention:
If a user loses both their authenticator app and their backup codes, an administrator can disable 2FA for that user's account:
- Go to
Administration
->Users
. - Find the user and edit their profile.
- In the user's settings/profile (often under an "Actions" menu or within the main edit page), there should be an option to "Disable Two-Factor Authentication" or "Reset 2FA" for that user.
- After the admin disables it, the user can log in with just their password and then re-enroll in 2FA.
Enabling and encouraging (or enforcing, for privileged accounts) 2FA is a significant step in improving the overall security posture of your Rocket.Chat deployment.
Workshop Enabling and Using Two-Factor Authentication
Objective
To configure Two-Factor Authentication (TOTP) as an administrator and then, as a regular user, enroll in 2FA using an authenticator app.
Prerequisites
- A running Rocket.Chat instance with administrator access.
- At least one non-admin user account (e.g.,
testuser1
from a previous workshop, or create a new one). - An authenticator app installed on your smartphone or desktop (e.g., Google Authenticator, Authy, FreeOTP, Microsoft Authenticator, or the built-in authenticator in password managers like Bitwarden or 1Password).
- Access to the non-admin user's credentials (username and password).
Steps
Part 1 Admin Configuration
-
Log in as Administrator: Log in to Rocket.Chat using your administrator account.
-
Navigate to 2FA Settings:
- Click your avatar (top-left) ->
Administration
. - In the left sidebar of the Administration panel, type
Two Factor
in the search bar, or navigate toWorkspace
(orSettings
) ->Accounts
(orPermissions
/Security
depending on version) ->Two Factor Authentication
. The exact path can vary slightly between Rocket.Chat versions. A general search for "Two Factor" in the admin settings is usually reliable.
- Click your avatar (top-left) ->
-
Enable TOTP:
- Find the setting "Enable Two Factor Authentication" and set its value to
True
(or toggle the switch ON). - Under "Allow users to enable Two Factor Authentication via":
- Ensure "TOTP" is enabled (set to
True
or checkbox checked). - For this workshop, you can leave "Email" disabled or disabled if it's an option, to focus on TOTP.
- Ensure "TOTP" is enabled (set to
- (Optional but Recommended for Admins) Enforce 2FA for Admin Role:
Find the setting "Enforce Two Factor Authentication for users with role(s)". In the input field, type
admin
and select it. This means any user with theadmin
role will be required to set up 2FA. Caution: If you enforce this for your current admin account, you will be prompted to set up 2FA for your admin account upon your next settings change or login. Be prepared with your authenticator app.
- Find the setting "Enable Two Factor Authentication" and set its value to
-
Save Changes: Scroll to the top or bottom of the settings page and click the "Save changes" button. You might be prompted for your admin password to confirm. If you enforced 2FA for admins, you might be immediately guided to set up 2FA for your admin account now. Follow the on-screen prompts (scan QR code, enter TOTP) if this happens.
Part 2 User Enrollment (Using a Non-Admin Account)
Now, let's switch to a regular user account to enroll in 2FA. If you enforced 2FA for admins in the previous step, you might have already done a similar process for your admin account. This part simulates what a standard user would do.
-
Log Out as Admin (or Use a Different Browser/Incognito Window): Log out of your admin account. It's best to use a different browser or an incognito/private window for the non-admin user to avoid session conflicts.
-
Log in as Non-Admin User: Log in to Rocket.Chat with the credentials of your non-admin test user (e.g.,
testuser1
). -
Navigate to Account Security Settings:
- Once logged in, click the user's avatar (top-left).
- Select "My Account" from the dropdown.
- In the "My Account" panel, look for a "Security" tab or section on the left. Click it.
-
Enable Two-Factor Authentication (TOTP):
- You should see an option like "Two-Factor Authentication (TOTP)" with a button to "Enable TOTP" or "Register TOTP". Click this button.
- A dialog box will appear. It will likely ask you to confirm your current password. Enter the user's password and click "Continue" or "Submit".
-
Scan QR Code and Get Backup Codes:
- A new dialog will appear displaying:
- A QR code.
- A Secret Key (a string of characters, this is the same information as the QR code but in text form).
- Backup Codes: A list of one-time backup codes will be displayed. This is a critical step.
- Action: Carefully copy these backup codes and store them in a very secure location (e.g., print them, save them in a password manager). Do not skip this. For the workshop, you can copy them to a temporary text file, but emphasize that in a real scenario, this needs secure storage.
- There might be a button to "Download backup codes" or "Copy codes".
- A new dialog will appear displaying:
-
Set Up Authenticator App:
- Open your authenticator app on your smartphone (e.g., Google Authenticator, Authy, etc.).
- In the app, choose to add a new account (often a
+
button). - Select the option to scan a QR code.
- Use your phone's camera to scan the QR code displayed by Rocket.Chat.
- Your authenticator app should recognize it and add an entry for your Rocket.Chat account (e.g.,
testuser1@chat.example.com
). It will immediately start generating 6-digit codes that refresh every 30 seconds.
-
Verify and Activate TOTP in Rocket.Chat:
- Back in the Rocket.Chat dialog (where the QR code and backup codes are shown), there will be an input field labeled "Authentication code" or "Verification code".
- Enter the current 6-digit code displayed in your authenticator app for your Rocket.Chat account into this field.
- Click the "Verify", "Enable", or "Register" button.
-
Confirmation:
- If the code is correct and your password (if asked again) was correct, you should see a success message indicating that 2FA (TOTP) has been enabled for your account.
- The "Enable TOTP" button in your Security settings might now change to "Disable TOTP", indicating it's active.
Part 3 Testing 2FA Login
-
Log Out: Log out of the
testuser1
account. -
Log In Again:
- Go to the Rocket.Chat login page.
- Enter the username (
testuser1
) and password for the account. Click "Login". - You should now be presented with a second screen prompting you for your "Authentication code" or "Two-Factor Code".
- Open your authenticator app, find the code for your Rocket.Chat account, and enter it into the field.
- Click "Login" or "Verify".
You should now be successfully logged into Rocket.Chat.
Part 4 (Optional) Testing Backup Code Usage
-
Initiate Login: Log out (if logged in) and attempt to log in again as
testuser1
up to the point where it asks for the 2FA code. -
Use a Backup Code:
- Instead of entering a code from your authenticator app, look for a link or button like "Use a backup code?" or "Enter recovery code". Click it.
- You'll be prompted to enter one of your backup codes.
- Retrieve one of the backup codes you saved earlier and enter it.
- Click "Login" or "Verify".
You should be logged in. Remember that each backup code can only be used once. Rocket.Chat might show you how many backup codes you have left or allow you to generate new ones if they run low (this functionality varies).
Part 5 (Optional) Admin Disabling 2FA for a User
Imagine testuser1
lost their phone and backup codes.
- Log in as Admin.
- Go to
Administration
->Users
. - Find
testuser1
in the list and click to edit/view their profile. - Look for an "Actions" menu (often three dots
...
) or a section in their profile related to 2FA. There should be an option like "Disable Two-Factor Authentication" or "Reset 2FA". Click it. - Confirm the action if prompted.
- Now,
testuser1
would be able to log in again with just their username and password, and they would need to re-enroll in 2FA if they wish.
Conclusion
In this workshop, you have successfully configured Two-Factor Authentication (TOTP) settings as an administrator in Rocket.Chat. You also walked through the process a regular user would follow to enroll their account in 2FA using an authenticator app, including the crucial step of saving backup codes. Finally, you tested the 2FA login process with both a TOTP code and a backup code, and saw how an admin can disable 2FA for a user if needed. Implementing and encouraging 2FA significantly enhances the security of your Rocket.Chat workspace by protecting accounts even if passwords are compromised.
Customizing Your Workspace
A key advantage of self-hosting Rocket.Chat is the ability to tailor the workspace to your organization's identity and preferences. Customization can range from simple branding changes like adding your logo and changing colors to more advanced modifications like custom CSS and UI layout adjustments. A well-customized workspace feels more professional, reinforces brand identity, and can improve user adoption and engagement.
Rocket.Chat offers a rich set of customization options through its Administration panel. Most visual customizations are found under Administration
-> Layout
or Administration
-> Settings
-> Layout
.
Branding (Logo, Colors, Custom CSS)
Branding is about making the Rocket.Chat interface visually align with your organization.
1. Logo and Favicon:
- Logo: This is the main image displayed in prominent places, such as the login screen, the top of the sidebar, and sometimes in headers.
- Location:
Administration
->Settings
->Layout
->Assets
(or similar path, search for "Assets"). - Formats: Typically supports PNG, JPG, and SVG. SVG is often preferred for scalability without loss of quality.
- Types:
- Logo (svg, png, jpg): The primary logo.
- Logo Dark (svg, png, jpg): A version of your logo suitable for dark themes if your workspace uses them.
- Login Page Logo (svg, png, jpg): A specific logo for the login page, which might be different or larger.
- How to Change: You'll usually see an option to "Upload" a new image file or "Reset" to the default Rocket.Chat logo. Pay attention to recommended dimensions or aspect ratios if provided, although Rocket.Chat often resizes images appropriately.
- Location:
- Favicon: The small icon displayed in browser tabs, bookmarks, and shortcuts.
- Location: Usually in the same
Assets
section. - Formats: Typically ICO, PNG. A square image is best. Common sizes are 16x16, 32x32, or 48x48 pixels.
- Types:
favicon.ico
favicon-16x16.png
favicon-32x32.png
favicon-96x96.png
(for Android home screen icons, etc.)apple-touch-icon.png
(for iOS home screen icons)
- How to Change: Upload your prepared favicon files. Some tools can generate all necessary favicon formats from a single source image.
- Location: Usually in the same
2. Colors:
Rocket.Chat allows you to customize the color scheme of the user interface to match your brand palette.
- Location:
Administration
->Settings
->Layout
->Colors
. - Customizable Elements: You can typically change colors for:
- Primary Background Color: The main background of the application.
- Secondary Background Color: Background for elements like sidebars or modals.
- Primary Text Color: Main text color.
- Secondary Text Color: Text color for less prominent text.
- Accent Color (or Link Color): Color used for links, buttons, and other interactive elements.
- Success, Warning, Danger Colors: Colors used for notifications and status indicators (e.g., green for success, red for error).
- Many more specific elements might be customizable depending on the Rocket.Chat version and theme system.
- How to Change: Colors are usually entered as hexadecimal color codes (e.g.,
#FFFFFF
for white,#003366
for a dark blue). You can use an online color picker tool to find the hex codes for your brand colors. As you change colors, the interface might update in real-time (or after a save and refresh) to show you a preview. - Themes: Rocket.Chat supports light and dark themes. You might be able to set different color palettes for each theme.
3. Custom CSS:
For more fine-grained control over the appearance beyond what the built-in color settings offer, Rocket.Chat allows administrators to add custom Cascading Style Sheets (CSS). This lets you override default styles, change fonts, adjust spacing, hide elements, or add new visual flairs.
- Location:
Administration
->Settings
->Layout
->Custom CSS
(or similar). - How to Use:
- You'll find a text area where you can input your CSS rules.
- To apply custom CSS effectively, you need some knowledge of CSS selectors and properties. You can use your browser's developer tools (usually opened by pressing F12) to inspect elements on your Rocket.Chat page, find their CSS classes or IDs, and then write CSS rules to target them.
- Example: To change the font family for the entire application:
- Example: To hide the "Create Channel" button for regular users (though permissions are a better way to control functionality):
!important
: While sometimes necessary to override deeply nested or highly specific default styles, use!important
sparingly, as it can make CSS harder to maintain. Try to use more specific selectors first.- Testing: Make small changes, save, and refresh your Rocket.Chat client to see the effect. Use browser developer tools extensively to test CSS rules before applying them globally.
- Caution: Incorrect or poorly written custom CSS can break the layout or functionality of Rocket.Chat. Always test thoroughly. Keep a backup of your custom CSS.
4. Custom Fonts:
If you want to use fonts that are not standard web fonts or not available by default, you can load them using custom CSS, typically with @font-face
rules.
- Steps:
- Host Font Files: You'll need the font files (e.g.,
.woff2
,.woff
,.ttf
) hosted somewhere accessible, either on your Rocket.Chat server (e.g., in a directory Nginx can serve) or via a font delivery service. If hosting yourself, you might need to configure Nginx to serve these font files with correct MIME types and CORS headers if they are on a different domain/subdomain. - Define
@font-face
in Custom CSS:Replace@font-face { font-family: 'YourCustomFont'; src: url('/path/to/yourcustomfont.woff2') format('woff2'), url('/path/to/yourcustomfont.woff') format('woff'); font-weight: normal; font-style: normal; }
/path/to/
with the actual URL where your font files are hosted. - Apply the Font: Use
font-family
in your custom CSS to apply the font to desired elements:
- Host Font Files: You'll need the font files (e.g.,
5. Custom JavaScript (Advanced and Use with Extreme Caution):
Some Rocket.Chat versions might offer a section for Custom JavaScript under Layout. This allows administrators to inject custom client-side JavaScript code into the application.
- Purpose: Can be used for advanced UI modifications, adding custom client-side integrations, or altering behavior in ways not possible with CSS or settings.
- Location:
Administration
->Settings
->Layout
->Custom Scripts
(or similar). - Risk: This is a very powerful feature and carries significant risk. Incorrect or malicious JavaScript can break your Rocket.Chat instance, introduce security vulnerabilities (like XSS if not handled carefully), or severely degrade performance.
- Recommendation:
- Avoid if possible. Prefer built-in settings, CSS, or official apps/integrations.
- If you must use it, ensure the code is thoroughly reviewed and tested.
- Understand the security implications deeply.
- This is generally for very advanced users or developers.
Workshop Customizing Your Rocket.Chat Branding
Objective
To apply basic branding customizations to your Rocket.Chat instance, including changing the logo, favicon, and primary interface colors. We will also explore adding a simple custom CSS rule.
Prerequisites
- A running Rocket.Chat instance with administrator access.
- A logo image file for your organization (e.g., PNG, JPG, or SVG format). A square or slightly wide logo often works best. For this workshop, you can use any sample image or create a simple one.
- A favicon image file (e.g., a small square PNG, like 32x32 pixels, or an ICO file). Many online tools can convert an image to an ICO file or generate multiple favicon sizes.
- Hexadecimal color codes for your desired brand colors (e.g., a primary accent color). You can use an online color picker like
htmlcolorcodes.com
to choose some.
Steps
1. Prepare Your Assets
- Logo: Have your logo file ready (e.g.,
my_logo.png
). - Favicon: Have your favicon file ready (e.g.,
my_favicon.png
orfavicon.ico
). - Colors: Choose a primary accent color (e.g., a shade of blue like
#00529B
or green like#2E7D32
).
2. Log in as Administrator
Log in to your Rocket.Chat instance using your administrator account.
3. Navigate to Layout Settings
- Click your avatar (top-left) ->
Administration
. - In the Administration panel's search bar, type
Layout
. Click on the "Layout" settings page when it appears (it might be under "Workspace" or "Settings").
4. Change Logo and Favicon
-
Access Assets Section: Within the Layout settings, find a section named "Assets" or similar (it might be a sub-tab or a collapsible section).
-
Upload Logo:
- Look for an option like "Logo (svg, png, jpg)". There should be an "Upload" button or a clickable area.
- Click it and select your prepared logo file (e.g.,
my_logo.png
) from your computer. - The logo should upload and a preview might appear.
- If there are separate options for "Logo Dark" or "Login Page Logo", you can upload appropriate versions there if you have them. For this workshop, changing the main logo is sufficient.
-
Upload Favicon:
- Look for options like "Favicon (ico, png)" or specific sizes (
favicon-16x16.png
,favicon-32x32.png
). - If there's a general "Favicon (ico)" upload, use your
.ico
file. - If there are options for PNG favicons, upload your small square PNG file (e.g.,
my_favicon.png
) to thefavicon-16x16.png
orfavicon-32x32.png
slot. Rocket.Chat might automatically generate other sizes from one of these. Some versions might prefer a single.ico
file that contains multiple resolutions. - If
apple-touch-icon.png
is an option, upload a slightly larger square PNG (e.g., 180x180 pixels) if you have one, for better display on Apple devices when added to the home screen.
- Look for options like "Favicon (ico, png)" or specific sizes (
-
Save Asset Changes: There might be a "Save changes" button specifically for the Assets section, or changes might be applied as you upload. If there is a main "Save changes" button at the top or bottom of the Layout page, click it after uploading your assets.
-
Verify Logo and Favicon:
- Refresh your browser (Ctrl+R or Cmd+R).
- You should see your new logo in the sidebar/header and your new favicon in the browser tab.
- Log out and check if the logo also appears on the login page (if you didn't set a specific login page logo, it usually defaults to the main logo).
5. Customize Colors
-
Access Colors Section: In the Layout settings page (
Administration
->Layout
), find a section or tab named "Colors". -
Change Primary Accent Color:
- Look for a color setting like "Primary Accent Color", "Link Color", "Button Color", or similar. The exact name might vary. It's often the color used for highlighting active elements, buttons, and links.
- Click on the color input field. A color picker might appear, or you can directly type your chosen hexadecimal color code (e.g.,
#00529B
). - As you change the color, you might see a live preview in the interface, or you might need to save.
-
Change Other Colors (Optional): Explore other available color settings (e.g., "Primary Background", "Secondary Background", "Primary Text Color") and try changing them to see their effect. Be mindful of contrast and readability. For example, if you set a dark background, ensure your text color is light.
-
Save Color Changes: Click the "Save changes" button (usually at the top or bottom of the page). You may need to refresh your browser window fully (sometimes a hard refresh
Ctrl+Shift+R
orCmd+Shift+R
is needed) to see all color changes applied. -
Verify Color Changes: Navigate through your Rocket.Chat interface (e.g., open channels, look at buttons, links) to see if your new color scheme is applied as expected.
6. Add Basic Custom CSS Let's add a simple custom CSS rule, for example, to slightly increase the font size of messages.
-
Access Custom CSS Section: In the Layout settings page (
Administration
->Layout
), find a section or tab named "Custom CSS". -
Add CSS Rule:
- In the text area provided for Custom CSS, add the following rule:
/* Increase font size of messages in the main chat area */ .rcx-message-body, .rcx-message-body p { font-size: 1.05em !important; /* Slightly larger text */ line-height: 1.5 !important; /* Adjust line spacing for readability */ }
.rcx-message-body
is a common class for the message content area in recent Rocket.Chat versions. The exact class name can change between versions. If this doesn't work, you'd need to use your browser's Developer Tools (F12 -> Inspect Element) to find the correct CSS selector for message text.font-size: 1.05em;
makes the font 5% larger than its parent.line-height: 1.5;
increases spacing between lines of text.!important
is used here to ensure our rule overrides existing styles. Use with care.
- In the text area provided for Custom CSS, add the following rule:
-
Save Custom CSS: Click the "Save changes" button.
-
Verify Custom CSS: Refresh your Rocket.Chat browser window. Go to a channel with messages and check if the message text appears slightly larger. If not, re-check the CSS selector using developer tools or try a different selector.
7. (Optional) Experiment and Revert * Try changing other colors or adding different simple CSS rules (e.g., change the color of channel names). * If you make a change you don't like, you can: * For colors: Reset them to default using a "Reset" button if available, or re-enter a previous color code. * For assets: Use the "Reset" button next to the asset to revert to the default Rocket.Chat logo/favicon. * For Custom CSS: Delete the CSS rules you added and save.
Conclusion
You have successfully customized the branding of your Rocket.Chat workspace by changing its logo, favicon, and primary colors. You also learned how to add a simple custom CSS rule to make minor visual adjustments. These customizations help make the platform feel unique to your organization and can improve the user experience. Remember that extensive CSS changes require careful testing across different parts of the application and can be affected by future Rocket.Chat updates.
Layout and UI Settings
Beyond branding, Rocket.Chat offers various settings to control the layout and behavior of the user interface. These settings can help streamline the user experience, hide or show certain UI elements, and tailor the interface to your team's workflow.
Location: Most of these settings are found under Administration
-> Settings
-> Layout
. Some might be under Administration
-> Settings
-> Accounts
or specific feature settings (like Livechat
).
Common Layout and UI Settings:
-
User Interface (Main Content):
- Display Avatars: Controls whether user avatars (profile pictures) are displayed next to messages in chat channels. Disabling this can make the interface cleaner but less personal.
- Group by Date: When enabled, messages in a channel are grouped under date separators (e.g., "Today", "Yesterday", "October 26").
- Use Real Names: If enabled, users' full names are displayed instead of (or in addition to) their usernames. This can improve readability and recognition.
- Sidebar Channel List Mode: Options like "Extended" (shows more info), "Medium", "Condensed".
- Display Roles: Show user roles next to their names in messages.
- Hide Usernames: If "Use Real Names" is enabled, this option might hide the username part if desired.
- Message Time Format: Customize how timestamps are displayed (e.g., 12-hour vs. 24-hour format).
- Desktop Notification Default Alert: Choose the default behavior for desktop notifications (e.g., All messages, Mentions only, Nothing). Users can usually override this in their personal settings.
- Mobile Notification Default Alert: Similar to desktop notifications, but for mobile devices.
-
Sidebar and Footer:
- Sidebar Header / Footer: Some versions allow adding custom HTML content to the top or bottom of the left sidebar. This could be used for important links, announcements, or branding elements.
- Hide Right Sidebar With Click: Whether clicking in the main chat area closes an open right sidebar (e.g., user info, threads).
- Display Avatars in Sidebar: Show user avatars in the sidebar channel list.
-
Home Page / Landing Page:
- Show Home Button: Whether to display a "Home" button that leads to a customizable home page experience.
- Home Title, Home Body (Content): Allows administrators to set custom content for the workspace's home page. This could be a welcome message, links to important channels, news, or guidelines. Supports Markdown.
- First Channel After Login: Specify a default channel that users are directed to after logging in if they haven't been in a channel before. Often defaults to
#general
.
-
Custom Sounds (Notification Sounds):
- Location:
Administration
->Settings
->Sounds
- Allows uploading custom sound files (e.g., MP3, WAV, OGG) to be used for different notification events (e.g., new message, private mention).
- You can then assign these custom sounds to specific notification types. This can be a fun way to personalize the workspace or use brand-specific audio cues.
- Location:
-
Embed Layout (For embedding Rocket.Chat into other websites):
- Location:
Administration
->Settings
->Layout
->Embed Layout
(or similar) - If you plan to embed your Rocket.Chat instance (or parts of it, like Livechat) into another website using an iframe, these settings control the appearance of the embedded view.
- Hide Header, Hide Footer, Hide Avatars: Options to create a more minimal interface suitable for embedding.
- Round Avatars: Whether avatars should be circular in the embedded view.
- Location:
-
Login Page Layout:
- Location:
Administration
->Settings
->Layout
->Login
- Login Terms / Privacy Policy / Legal URL: Links to your organization's terms of service, privacy policy, etc., displayed on the login/registration pages.
- Background URL: Set a custom background image for the login page.
- Custom Logo for Login Page: (Covered in Branding)
- Show/Hide "Forgot Password" link, "Register" link, etc.
- Location:
-
Message Box Layout:
- Location:
Administration
->Settings
->Layout
->Message Box
- Allow Message Formatting using Markdown: Enable/disable Markdown support in messages.
- Action Links Layout: How action links (e.g., from integrations) are displayed.
- Location:
-
Mobile Layout:
- Specific settings that might affect the mobile app experience if not controlled by the app itself. Often fewer options here as mobile apps have their own rendering.
Best Practices for UI Customization: * Consider User Experience (UX): Changes should ideally make the interface more intuitive and efficient, not more cluttered or confusing. * Maintain Readability and Accessibility: Ensure good color contrast, legible font sizes, and that important information is clearly visible. * Consistency: Try to maintain a consistent look and feel throughout the application. * Test Thoroughly: After making changes, test on different devices and screen sizes, and with different user roles, to ensure everything looks and works as expected. * Less is Often More: Avoid overwhelming users with too many visual elements or drastic changes unless there's a clear benefit. * Inform Users of Major Changes: If you make significant UI changes, communicate them to your users to avoid confusion.
Many of these settings are straightforward toggles or input fields. The best way to understand their impact is to experiment with them in a test environment or during off-peak hours, observe the changes, and revert if necessary. Always remember to "Save changes" after modifying settings.
Email Configuration (SMTP)
For your Rocket.Chat server to send emails (e.g., for password resets, email notifications for mentions/DMs, user invitations, email verification), you need to configure an SMTP (Simple Mail Transfer Protocol) server. Rocket.Chat acts as an SMTP client, connecting to an SMTP server you provide, which then handles the actual email delivery.
Why is SMTP configuration crucial? * Password Resets: Users who forget their passwords rely on email-based reset links. * Email Notifications: Users can opt to receive email notifications for messages when they are offline or haven't read them. * User Invitations: Inviting new users via email requires a working SMTP setup. * Email Verification: If you require users to verify their email addresses upon registration. * System Notifications: Admins might receive important system notifications via email.
You have several options for an SMTP server:
-
Transactional Email Services (Recommended for Reliability):
- These are third-party services specializing in sending application-generated emails (transactional emails). They typically offer better deliverability rates, spam filtering, tracking, and analytics compared to using a generic ISP's SMTP server or your own mail server.
- Examples:
- SendGrid: Popular, offers a generous free tier.
- Mailgun: Developer-focused, robust API, also has a free tier.
- Amazon SES (Simple Email Service): Cost-effective, integrates well with AWS, but might have a steeper initial setup curve and sending limits for new accounts.
- Postmark: Known for high deliverability for transactional emails.
- Brevo (formerly Sendinblue): Offers email marketing and transactional SMTP.
- Setup: You sign up for the service, verify your sending domain (to improve deliverability and prove you own the domain you're sending from), and they provide you with SMTP credentials (server address, port, username, password).
-
Your Own Mail Server:
- If your organization or university already runs its own mail server (e.g., Postfix, Exim, Microsoft Exchange), you can often configure it to allow Rocket.Chat to relay emails through it. This requires coordination with your email administrators.
-
Gmail/Google Workspace SMTP Relay (Use with Caution for High Volume):
- You can use Gmail's SMTP servers (
smtp.gmail.com
) to send emails. - Limitations: Gmail has sending limits (e.g., 500 emails per day for a standard Gmail account, higher for Google Workspace). Exceeding these limits can get your account temporarily blocked.
- Security: You'll typically need to enable "Less secure app access" for your Google account or, preferably, generate an "App Password" specifically for Rocket.Chat. Using an App Password is more secure as it doesn't expose your main Google account password.
- Not ideal for large deployments due to sending limits, but can work for small personal instances or testing.
- You can use Gmail's SMTP servers (
-
Your ISP's SMTP Server (Often problematic):
- Some Internet Service Providers (ISPs) offer SMTP server access. However, these are often heavily restricted, may have poor deliverability for application emails (often flagged as spam), and are generally not recommended for server applications.
Setting Up an SMTP Relay
Let's assume you've chosen an SMTP provider (e.g., SendGrid, Mailgun, or Gmail with an App Password) and have the following details:
* SMTP Server Hostname: e.g., smtp.sendgrid.net
, smtp.mailgun.org
, smtp.gmail.com
* SMTP Port:
* 587
(TLS/STARTTLS - recommended)
* 465
(SSL - older, but still common)
* 25
(Plain text or STARTTLS - often blocked by ISPs for outbound connections to prevent spam, not recommended without STARTTLS)
* SMTP Username: Your login username for the SMTP service.
* SMTP Password: Your password or API key for the SMTP service (for Gmail, use an App Password).
* From Email Address: The email address that will appear as the sender (e.g., noreply@chat.example.com
, support@yourcompany.com
). This address should ideally be on a domain you've verified with your transactional email provider to improve deliverability.
Configuring SMTP in Rocket.Chat:
-
Navigate to Email Settings:
- Log in to Rocket.Chat as an administrator.
- Go to
Administration
->Settings
. - In the Settings search bar, type
Email
orSMTP
, or navigate toEmail
->SMTP
.
-
Enter SMTP Configuration Details:
- Protocol: Choose
smtp
orsmtps
.smtp
: Typically used with port 587 (STARTTLS) or port 25.smtps
: Typically used with port 465 (SSL direct connection). If unsure, start withsmtp
and port 587.
- Host: Enter your SMTP server hostname (e.g.,
smtp.sendgrid.net
). - Port: Enter the SMTP port (e.g.,
587
or465
). - Username: Enter your SMTP username.
- Password: Enter your SMTP password or App Password.
- Enable TLS/SSL for SMTP (or similar wording like "Ignore TLS"):
- If using port 587 (STARTTLS), this should generally be enabled or there might be an option like "Ignore TLS" which should be set to
False
. STARTTLS begins as a plain connection and then upgrades to TLS. - If using port 465 (SSL), the connection is encrypted from the start. Ensure any "Ignore TLS" or "Disable SSL/TLS" option is off.
- The exact wording can vary. The goal is to ensure your connection to the SMTP server is encrypted. Consult your SMTP provider's documentation.
- If using port 587 (STARTTLS), this should generally be enabled or there might be an option like "Ignore TLS" which should be set to
- From Email: Enter the email address that should appear as the sender (e.g.,
noreply@chat.example.com
ornotifications@chat.example.com
).- Important for Deliverability: This email address should ideally be from a domain you own and have configured SPF, DKIM, and DMARC records for in your DNS settings. These records help prove to receiving mail servers that the email is legitimate and not spam, significantly improving deliverability. Transactional email services provide guidance on setting these up.
- Pool Options (Advanced):
maxConnections
: Maximum number of concurrent connections to the SMTP server. Default is usually fine.maxMessages
: Maximum number of messages to send through a single connection. Usually, default pool options are sufficient unless you're sending a very high volume of emails.
- Protocol: Choose
-
Save Changes: Click the "Save changes" button at the top or bottom of the page.
-
Test Email Sending:
- After saving the settings, Rocket.Chat usually provides a "Send a test mail to my user" button or similar in the SMTP settings section.
- Click this button. Rocket.Chat will attempt to send a test email to the email address associated with your currently logged-in administrator account.
- Check your email inbox (and spam folder) for the test email. If you receive it, your SMTP configuration is likely correct.
- If you don't receive it, or if Rocket.Chat shows an error:
- Double-check all SMTP credentials (host, port, username, password). Typos are common.
- Verify your firewall (if any on your Rocket.Chat server) allows outgoing connections on the SMTP port you configured (e.g., 587 or 465).
ufw
usually allows all outgoing by default, but restrictive egress firewalls might block it. - Check Rocket.Chat logs for more detailed error messages (
Administration
->View Logs
). - Consult your SMTP provider's documentation for troubleshooting tips or check their status page.
- For Gmail: Ensure "Less secure app access" is enabled or you're using a correctly generated App Password. Check your Google account's security activity for blocked sign-in attempts.
- Ensure your "From Email" is authorized by your SMTP provider.
Additional Email Settings in Rocket.Chat:
(Found under Administration
-> Settings
-> Email
)
- Email Footer: Add custom text or HTML to the footer of all emails sent by Rocket.Chat.
- Subject Prefixes: Add prefixes to email subjects (e.g.,
[YourOrg Chat] New Message
). - Various Notification Preferences: Control when and how email notifications are sent (e.g., "Email Notification for Offline Users," "Group Mentions," etc.).
Configuring SMTP correctly is essential for a fully functional Rocket.Chat instance. Choosing a reliable transactional email service and properly configuring DNS records (SPF, DKIM, DMARC) for your sending domain are key to ensuring your emails reach users' inboxes.
Workshop Configuring Email Notifications via SMTP
Objective
To configure Rocket.Chat to send emails using an external SMTP service, enabling features like password resets and email notifications. We will use SendGrid's free tier as an example, but the principles apply to other SMTP providers like Mailgun, Amazon SES, or even Gmail (using an App Password).
Prerequisites
- A running Rocket.Chat instance with administrator access.
- An account with an SMTP provider. For this workshop, we'll outline steps for SendGrid. If using another service:
- SendGrid: Sign up for a free account at sendgrid.com. You'll need to create and verify a "Sender Identity" (either a single email address or an entire domain).
- Gmail: Your Gmail/Google Workspace account. You will need to generate an "App Password" for Rocket.Chat. Go to your Google Account -> Security -> 2-Step Verification (must be enabled) -> App passwords.
- Other provider: Obtain your SMTP host, port, username, and password.
- The email address associated with your Rocket.Chat admin account must be a real, accessible email address where you can receive the test email.
- Your domain name (e.g.,
chat.example.com
) and access to its DNS settings if you want to improve deliverability by setting up SPF/DKIM (recommended, but can be skipped for initial testing).
Steps
1. Obtain SMTP Server Details
Scenario A Using SendGrid (Recommended for Deliverability)
- Sign up/Log in to SendGrid: Go to sendgrid.com and create an account or log in.
- Create a Sender Identity:
- In the SendGrid dashboard, navigate to
Settings
->Sender Authentication
. - You can either verify a Single Sender (an email address) or Authenticate a Domain. Authenticating a domain is better for deliverability but requires DNS changes. For quick testing, Single Sender verification is easier.
- Follow SendGrid's instructions to verify your chosen sender email address (e.g.,
noreply@yourdomain.com
or even your personal email for testing). You'll typically receive a verification email.
- In the SendGrid dashboard, navigate to
- Create an API Key (to be used as SMTP Password):
- In SendGrid, navigate to
Settings
->API Keys
. - Click "Create API Key".
- Give it a name (e.g.,
RocketChat SMTP
). - Choose "Full Access" or "Restricted Access" (if restricted, ensure it has "Mail Send" permissions). For simplicity in this workshop, "Full Access" is fine, but for production, least privilege is better.
- Click "Create & View". SendGrid will show you the API key only once. Copy it immediately and store it securely. This API key will be your SMTP password.
- In SendGrid, navigate to
- Get SendGrid SMTP Details:
- SMTP Server:
smtp.sendgrid.net
- SMTP Ports:
587
(recommended, uses STARTTLS),25
, or465
(SSL). We'll use587
. - SMTP Username: The literal string
apikey
(yes, just "apikey"). - SMTP Password: The API key you just created.
- From Email: The email address you verified as a Sender Identity.
- SMTP Server:
Scenario B Using Gmail/Google Workspace SMTP (For Small Scale/Testing Only)
- Enable 2-Step Verification for your Google Account: This is required to generate App Passwords. Go to
myaccount.google.com
->Security
->2-Step Verification
. - Generate an App Password:
- Go to
myaccount.google.com
->Security
. - Under "Signing in to Google," click
App passwords
(you might need to re-enter your Google password). - If you don't see "App passwords," you might need to enable 2-Step Verification first.
- In "Select app," choose "Mail".
- In "Select device," choose "Other (Custom name)" and enter a name like
RocketChat Server
. - Click "Generate".
- Google will display a 16-character App Password. Copy this password immediately and store it securely. This will be your SMTP password for Rocket.Chat. Do not use spaces in the password.
- Go to
- Get Gmail SMTP Details:
- SMTP Server:
smtp.gmail.com
- SMTP Port:
587
(for TLS/STARTTLS) or465
(for SSL). We'll use587
. - SMTP Username: Your full Gmail address (e.g.,
your.email@gmail.com
). - SMTP Password: The 16-character App Password you generated.
- From Email: Your Gmail address.
- SMTP Server:
2. Navigate to Email Settings in Rocket.Chat
* Log in to your Rocket.Chat instance as an administrator.
* Click your avatar (top-left) -> Administration
.
* In the Administration panel's search bar, type SMTP
. Click on SMTP
under the Email
category.
3. Configure SMTP Settings Fill in the SMTP details you obtained in Step 1.
-
If using SendGrid:
- Protocol:
smtp
(or leave as default if it doesn't explicitly ask and assumes STARTTLS with port 587) - Host:
smtp.sendgrid.net
- Port:
587
- Username:
apikey
(the literal word) - Password: Your SendGrid API Key.
- Enable TLS/SSL for SMTP (or similar): Ensure this is enabled (or if there's an "Ignore TLS", ensure it's
False
/unchecked). SendGrid expects STARTTLS on port 587. - From Email: Your verified SendGrid Sender Identity email address (e.g.,
noreply@chat.example.com
).
- Protocol:
-
If using Gmail:
- Protocol:
smtp
- Host:
smtp.gmail.com
- Port:
587
- Username: Your full Gmail address (e.g.,
your.email@gmail.com
). - Password: Your 16-character Google App Password.
- Enable TLS/SSL for SMTP (or similar): Ensure this is enabled (or "Ignore TLS" is
False
/unchecked). - From Email: Your Gmail address.
- Protocol:
-
Common fields for both:
- Pool (Checkbox): Usually can be left unchecked/disabled for basic setup unless you understand its implications.
- Other pool options (
maxConnections
,maxMessages
, etc.) can usually be left at their defaults.
4. Save Changes Scroll to the top or bottom of the SMTP settings page and click the "Save changes" button.
5. Test Email Configuration
- Use the Test Button: On the SMTP settings page, there should be a button labeled "Send a test mail to my user" or similar. Click this button.
- Check Your Email: The test email will be sent to the email address associated with your currently logged-in Rocket.Chat administrator account. Check that email account's inbox. Also, check the spam/junk folder, as initial emails from a new setup might sometimes be misclassified.
- Success Message: If the configuration is correct, Rocket.Chat should display a success message (e.g., "Test mail sent!").
- Email Content: The test email should have a subject like "Test mail from chat.example.com" and some body content confirming it's a test.
6. Troubleshoot Common Issues If you don't receive the test email or Rocket.Chat shows an error:
- Check Rocket.Chat Logs: Go to
Administration
->Workspace
->View Logs
. Look for any error messages related toEmail
orSMTP
. This often provides clues (e.g., authentication failure, connection timeout, incorrect hostname).- Example error:
Error sending test email: Mail command failed: 535-5.7.8 Username and Password not accepted.
(This indicates an authentication issue with your SMTP provider). - Example error:
Error sending test email: queryA ETIMEOUT smtp.example.com
(This indicates a DNS resolution problem or that the SMTP host is unreachable).
- Example error:
- Verify Credentials:
- Double-check your SMTP Host, Port, Username, and Password for typos.
- For SendGrid: Ensure you're using
apikey
as the username and the full API key as the password. Ensure the API key has mail sending permissions. - For Gmail: Ensure you're using the full email address as the username and the 16-character App Password (not your regular Google password). Ensure 2-Step Verification is enabled. Check your Google Account's "Security" section for any "Critical security alerts" related to blocked sign-in attempts.
- Firewall: Ensure your server's firewall (e.g.,
ufw
on the host, or any cloud provider firewall) allows outgoing connections on the SMTP port you are using (e.g., 587 TCP or 465 TCP). Most defaultufw
configurations (sudo ufw default allow outgoing
) allow this. - SMTP Provider Limits/Status:
- Check if your SMTP provider has any daily/hourly sending limits that you might have hit (unlikely with just one test email, but good to know).
- Check your SMTP provider's status page for any ongoing incidents.
- From Email Address: Ensure the "From Email" you configured in Rocket.Chat is authorized to send emails by your SMTP provider. For SendGrid, it must be a verified Sender Identity. For Gmail, it's your Gmail address.
- Port and Encryption Mismatch: Ensure the port number matches the expected encryption method:
- Port 587: Expects STARTTLS (connection starts unencrypted, then upgrades to TLS). The "Enable TLS/SSL" option in Rocket.Chat should reflect this (usually means enabled, or "Ignore TLS" disabled).
- Port 465: Expects SSL/TLS from the beginning.
- Port 25: Can be plain text or STARTTLS. Often blocked by hosting providers. Avoid if possible unless you know what you're doing and are using STARTTLS. Try toggling the TLS/SSL setting in Rocket.Chat if one combination doesn't work.
- (Advanced) DNS Deliverability (SPF, DKIM, DMARC): While not strictly required for the email to send, lack of these DNS records makes it highly likely your emails will go to spam or be rejected.
- SPF (Sender Policy Framework): A TXT DNS record that lists which mail servers are authorized to send email on behalf of your domain.
- DKIM (DomainKeys Identified Mail): Adds a digital signature to outgoing emails, allowing receiving servers to verify the email's authenticity. Transactional email providers will give you a DKIM record (often a CNAME or TXT record) to add to your DNS.
- DMARC (Domain-based Message Authentication, Reporting, and Conformance): A TXT DNS record that tells receiving mail servers what to do with emails that fail SPF or DKIM checks (e.g., quarantine, reject, or do nothing). It also provides reporting. Your SMTP provider (SendGrid, Mailgun, etc.) will have detailed guides on setting these up for your domain. This is crucial for production email deliverability.
7. (Optional) Configure Other Email Settings
Once SMTP is working, explore other email settings:
* Go to Administration
-> Settings
-> Email
.
* Email Footer: Add a custom footer, e.g., © Your Organization Name
.
* Subject Prefix: Set a prefix for subjects, e.g., [MyTeam Chat]
.
* Review notification settings under Administration
-> Settings
-> Accounts
-> Default User Preferences
(e.g., "Enable Auto-Away", "Idle Time Limit") and how they interact with email notifications for offline users. Also, users can set their own notification preferences in "My Account" -> "Preferences" -> "Notifications".
Conclusion
You have now configured Rocket.Chat to send emails using an external SMTP provider. This enables critical functionalities like password resets, user invitations, and email notifications for offline activity. You learned how to obtain SMTP credentials from services like SendGrid or Gmail (using App Passwords) and how to input them into Rocket.Chat. Troubleshooting common issues was also covered. For reliable email delivery in a production environment, remember the importance of configuring SPF, DKIM, and DMARC records for your sending domain.
Managing Channels and Discussions
Effective communication in a team chat platform hinges on well-organized channels and clear discussion threads. Rocket.Chat offers robust features for managing different types of conversations, from broad public announcements to focused private team discussions and direct one-on-one messages. Understanding these features allows administrators and users to create a structured and productive communication environment.
Public vs. Private Channels
Channels are the primary spaces for group conversations in Rocket.Chat. They can be either public or private.
-
Public Channels (often denoted with
#
prefix, e.g.,#general
)- Visibility: Discoverable and joinable by any registered user in the workspace.
- Access: Any user can view the channel history (unless configured otherwise) and participate in discussions.
- Use Cases:
- General announcements (e.g.,
#announcements
). - Company-wide discussions (e.g.,
#general
,#random
). - Open project discussions where input from anyone is welcome (e.g.,
#project-alpha-feedback
). - Interest groups (e.g.,
#book-club
,#tech-talks
).
- General announcements (e.g.,
- Creation: By default, any user can create a public channel, but administrators can restrict this permission (
Create Public Channels
permission, found inAdministration
->Permissions
). - Moderation: Channel owners/moderators can manage messages and members within the channel.
-
Private Channels (often denoted with a lock icon
🔒
and sometimes referred to as Private Groups)- Visibility: Not listed in the public channel directory. Users cannot see or find them unless they are invited.
- Access: Strictly by invitation only. Only members of the private channel can view its content and participate.
- Use Cases:
- Specific project teams (e.g.,
🔒project-phoenix-core
). - Departmental discussions (e.g.,
🔒marketing-team
). - Sensitive topics requiring confidentiality.
- Management discussions.
- Specific project teams (e.g.,
- Creation: By default, any user can create a private channel. This can also be restricted by administrators (
Create Private Channels
permission). - Membership: Managed by channel owners/moderators. They can invite and remove members.
- Security: While private, messages are still stored on the server and accessible to administrators with database access. For true end-to-end encrypted conversations (where even server admins cannot read messages), Rocket.Chat has been developing E2EE features, which might require specific setup and have certain limitations.
Key Differences Summarized:
Feature | Public Channel | Private Channel |
---|---|---|
Symbol | # |
🔒 |
Discoverability | Yes, by all users | No, only by members |
Join Method | Self-join | Invitation only |
Message Access | All users (typically) | Members only |
Use Cases | Open discussion, announcements | Focused teams, sensitive topics |
Read-Only Channels:
Both public and private channels can be set to "Read-Only." In a read-only channel, only users with specific permissions (e.g., channel owners, moderators, or users with a post-readonly
permission) can send messages. Other members can only read.
* Use Cases: Announcement channels, channels for broadcasting information where discussion is not desired or should happen elsewhere (e.g., in threads).
* Setting: This is a channel setting managed by the channel owner/moderator.
Creating and Managing Teams
Rocket.Chat's "Teams" feature provides a way to group multiple related channels and users under a single umbrella. This is particularly useful for larger organizations or complex projects where multiple channels are needed for different aspects of a team's work.
- Concept: A Team can be thought of as a super-channel that contains other sub-channels.
- When you create a Team, a main channel for that Team is automatically created.
- You can then add existing channels to the Team or create new channels specifically within that Team.
- Membership:
- Users added to a Team are automatically added to the Team's main channel.
- You can configure whether Team members are automatically added to all sub-channels within the Team, or if they need to join/be invited to sub-channels individually (providing more granular control).
- Teams can be public (anyone can join the Team and its public sub-channels) or private (invitation-only for the Team and its private sub-channels).
- Benefits:
- Organization: Helps organize a large number of channels by grouping them logically.
- Discoverability: Makes it easier for team members to find all relevant channels for their team.
- Permissions: Can simplify permission management if permissions are inherited or managed at the Team level (though channel-level permissions still apply).
- Unified Space: Provides a dedicated space for a specific department, project, or group, reducing clutter in the main channel list.
- How to Create a Team:
- In the Rocket.Chat sidebar, look for a "Create" button or menu (often a
+
icon). - Select "Team" from the creation options.
- Team Name: Give your Team a descriptive name (e.g.,
Marketing Department
,Project Titan
). - Description (Optional): Add a brief description of the Team's purpose.
- Privacy: Choose whether the Team is Public or Private.
- Members (Optional): You can invite initial members during creation.
- Channels (Optional): You can add existing channels to the Team or choose to create them later.
- Settings: Configure options like whether members are auto-joined to all Team channels.
- Click "Create".
- In the Rocket.Chat sidebar, look for a "Create" button or menu (often a
- Managing a Team:
- Once created, you can access Team settings by clicking the Team name and looking for a "Team Info" or "Settings" option.
- From there, you can manage members, add/remove channels, change Team settings, and convert channels to be part of the Team or remove them.
Threaded Discussions and Direct Messages
To keep main channel conversations focused and reduce noise, Rocket.Chat offers threaded discussions and direct messages.
-
Threaded Discussions (Threads):
- Purpose: Allow users to have side conversations related to a specific message in a channel or direct message without cluttering the main chat flow.
- How it Works:
- Hover over a message you want to reply to in a thread.
- Click the "Reply in Thread" icon (often looks like a speech bubble).
- This opens a right-hand sidebar where the threaded conversation takes place.
- Replies within the thread are kept separate from the main channel but are linked to the original message.
- The original message in the channel will often show an indicator that there are thread replies (e.g., "X replies").
- Benefits:
- Keeps main channels clean and on-topic.
- Allows for focused discussions on specific points.
- Participants in a thread receive notifications for new replies in that thread.
- Users can "follow" threads to stay updated even if they don't participate.
- Discussions vs. Threads: Rocket.Chat has had both "Discussions" and "Threads." They are very similar concepts, with "Threads" often being the more modern implementation. A "Discussion" might create a temporary, named sub-conversation linked to a message, while a "Thread" is a more direct reply chain. The exact UI and terminology might evolve. The core idea is the same: branching off a message for a focused sub-conversation.
-
Direct Messages (DMs):
- Purpose: For one-on-one private conversations between two users.
- How it Works:
- Users can find another user in the directory or by searching.
- Clicking on a user's name usually opens a direct message conversation with them.
- Direct Message Groups: Rocket.Chat also supports multi-person direct messages, allowing small groups (e.g., 3-8 people) to have a private conversation without creating a formal private channel. This is useful for quick, ad-hoc group chats.
- Visibility: DM content is private to the participants. Administrators with database access could technically see them, but they are not publicly visible.
Moderation Tools
Moderation is key to maintaining a healthy and productive chat environment, especially in public channels or larger communities. Rocket.Chat provides various tools for channel owners and moderators.
- Assigning Moderators:
- Channel owners can assign the
moderator
role to other users within that specific channel. - Go to Channel Info -> Members -> Find user -> Click three-dots menu -> Set as Moderator.
- Global moderators (with the
moderator
role assigned system-wide) also have moderation powers in public channels.
- Channel owners can assign the
- Moderation Actions (typically available to channel owners/moderators by clicking the three-dots menu on a message):
- Delete Message: Remove inappropriate or off-topic messages. A record of deletion might be kept in audit logs.
- Edit Message: Correct typos or clarify information in someone else's message (permission-dependent).
- Quote Message: Reply to a specific message by quoting it.
- Star Message: Mark important messages.
- Pin Message: Pin important messages to the top of the channel for visibility. Pinned messages are easily accessible from the channel info panel.
- Report Message: Allows users to report inappropriate messages to administrators/moderators.
- User-Level Moderation (within a channel):
- Remove User: Kick a user from a channel. In private channels, they would need to be re-invited. In public channels, they could rejoin unless banned.
- Mute User (in channel): Prevent a specific user from sending messages in that channel for a period or indefinitely.
- Set User as Owner/Moderator: Promote other users within the channel.
- Channel Settings (managed by channel owners/moderators):
- Channel Name, Topic, Announcement, Description: Edit these informative fields. Announcements appear as a banner at the top.
- Read-Only: Toggle read-only mode for the channel.
- Prune Messages: Delete messages older than a certain date or all messages. Use with extreme caution.
- Hide System Messages: Choose whether system messages (e.g., "User X joined the channel," "User Y left the channel") are displayed.
- Allow Reacting: Enable/disable message reactions (emojis).
- Broadcast Channel: Similar to read-only, but specifically designed for announcements. Only users with permission can post.
- Permissions System (Admin controlled):
- Administrators have fine-grained control over what different roles can do via
Administration
->Workspace
->Permissions
. - This is where you can define who can delete messages (their own vs. others'), who can edit messages, who can create channels, etc. This underpins the moderation capabilities.
- For example, the
delete-message
permission might be granted toowner
,moderator
, andadmin
roles, whiledelete-own-message
might be granted to theuser
role.
- Administrators have fine-grained control over what different roles can do via
Effectively using these channel management, discussion, and moderation tools helps ensure that your Rocket.Chat workspace remains organized, productive, and respectful. Training users on how to use threads and encouraging good communication etiquette are also important.
Workshop Effective Channel and Discussion Management
Objective
To practice creating different types of channels, organizing them into a Team, utilizing threaded discussions, and exploring basic moderation actions within a channel.
Prerequisites
- A running Rocket.Chat instance with administrator access (for creating Teams and initial setup).
- At least two user accounts:
- One administrator account (e.g.,
admin
). - One regular user account (e.g.,
testuser1
). If you don't have one, create it viaAdministration
->Users
->New
.
- One administrator account (e.g.,
- Logged into Rocket.Chat with both accounts, preferably in different browser windows or profiles, so you can see interactions from both perspectives.
Scenario
Imagine you are setting up Rocket.Chat for a university course, "Introduction to Astrophysics." You need: * A public channel for general course announcements and Q&A. * A private channel for teaching assistants (TAs) to coordinate. * A Team to group these course-related channels. * You also want to practice using threads and moderation.
Steps
Part 1 Creating Channels (as Admin)
-
Log in as Administrator.
-
Create a Public Channel for Course Announcements:
- In the left sidebar, click the "Create" button (often a
+
icon) next to "Channels" or near your avatar. - Select "Channel".
- Channel Name:
astro-101-announcements
(Channel names are usually lowercase, no spaces, can use hyphens). - Privacy: Keep "Public" selected (the default).
- Read-Only: Check this box. This channel is for announcements, so only authorized users (like admins or designated TAs) should post.
- Members (Optional): You can add
testuser1
now, or they can join later as it's public. Let's skip adding members for now. - Description (Optional):
Official announcements for ASTRO-101.
- Click "Create".
- In the left sidebar, click the "Create" button (often a
-
Create a Private Channel for TAs:
- Click the "Create" button again -> "Channel".
- Channel Name:
astro-101-tas-private
- Privacy: Select "Private".
- Read-Only: Keep this unchecked. TAs need to discuss freely.
- Members: Add your
testuser1
account to this private channel (search fortestuser1
and select them). As the creator, your admin account is automatically a member. - Description (Optional):
Coordination channel for ASTRO-101 TAs.
- Click "Create".
Part 2 Creating a Team (as Admin)
-
Create the "Astrophysics Course" Team:
- Click the "Create" button (near your avatar or in the sidebar).
- Select "Team".
- Team Name:
ASTRO-101 Course
- Privacy: Make this Team "Public" so students can find it.
- Description (Optional):
Main team for the Introduction to Astrophysics course.
- Members (Optional): Add
testuser1
. - Channels to Add (Optional):
- You should see your recently created channels. Select
astro-101-announcements
. - You can leave
astro-101-tas-private
out of the public team structure for now, or add it if TAs should also easily see it grouped this way (even if others can't access the channel itself). For this exercise, let's add it to see how it appears.
- You should see your recently created channels. Select
- Settings: Review options like "Automatically add new members to all channels" (for a public team with potentially many students, you might want this unchecked initially, so students join channels they need, but for a small course, auto-join might be fine). Let's leave it unchecked for now.
- Click "Create".
-
Explore the Team Structure:
- In your sidebar, you should now see the
ASTRO-101 Course
Team. - Expand it. You should see the
#astro-101-announcements
and🔒astro-101-tas-private
channels nested under it. - You'll also see a default channel for the Team itself, likely named
#astro-101-course
(or similar to the Team name). This is the main Team channel.
- In your sidebar, you should now see the
Part 3 User Interaction and Threaded Discussions
-
Log in as
testuser1
(Regular User) in a separate browser/window.testuser1
should see theASTRO-101 Course
Team in their sidebar because it's public and they were added as a member.- They should be able to access
#astro-101-announcements
and the main Team channel#astro-101-course
. - They should also see and be able to access
🔒astro-101-tas-private
because they were explicitly added as a member.
-
Post a Message and Start a Thread (as Admin in main Team channel):
- Switch to your Admin account.
- Go to the
#astro-101-course
channel (the main Team channel). - Post a message:
Welcome to ASTRO-101! The first lecture is on Monday at 9 AM. Any questions about the syllabus?
- Hover over your message. Click the "Reply in Thread" icon (speech bubble).
- A right sidebar will open for the thread. Add a reply in the thread:
The syllabus can be found here: [link to syllabus]
(you can just type some text).
-
Reply in Thread (as
testuser1
):- Switch to your
testuser1
account. - Go to the
#astro-101-course
channel. You should see the Admin's message with an indication of thread replies (e.g., "1 reply"). - Click on the "1 reply" link or hover over the message and click "Reply in Thread".
- The thread sidebar will open. Add a reply as
testuser1
:Thanks! Will the lectures be recorded?
- Switch to your
-
Observe Thread Behavior:
- Notice that
testuser1
's reply appears in the thread sidebar but not directly in the main#astro-101-course
channel, keeping the main channel cleaner. - The Admin (and other thread participants) will get notifications about new replies in the thread.
- Notice that
Part 4 Moderation Actions (as Admin)
-
Post a "Problematic" Message (as
testuser1
for simulation):- Switch to
testuser1
. - In the
#astro-101-course
channel (not the thread), post a slightly off-topic or test message:Can we discuss our favorite pizza toppings here? 🍕
- Switch to
-
Moderate the Message (as Admin):
- Switch to Admin.
- In the
#astro-101-course
channel, findtestuser1
's pizza message. - Hover over the message and click the three-dots menu ("More actions").
- Delete Message: Select "Delete". Confirm if prompted. The message should disappear.
- Observation: System messages about deletion might appear depending on channel settings.
-
Make
testuser1
a Moderator of the#astro-101-course
Channel (as Admin):- In the
#astro-101-course
channel, click the channel name/info icon (often ani
or three dots at the top of the chat view) to open the channel information panel. - Go to the "Members" tab.
- Find
testuser1
in the member list. - Click the three-dots menu next to
testuser1
's name. - Select "Set as moderator". Confirm.
testuser1
now has moderator privileges within this specific channel.
- In the
-
Pin a Message (as
testuser1
, now a channel moderator):- Switch to
testuser1
. - In
#astro-101-course
, find the Admin's original welcome message:Welcome to ASTRO-101! ...
- Hover over this message, click the three-dots menu.
- Select "Pin Message". Confirm.
- A system message will announce the pinned message. Pinned messages can be viewed from the channel info panel. This demonstrates that
testuser1
now has moderator rights in this channel.
- Switch to
-
Test Read-Only Channel (as
testuser1
):- As
testuser1
, try to post a message in the#astro-101-announcements
channel. - Since this channel was set to "Read-Only" and
testuser1
is not an owner/global admin (and we haven't given thempost-readonly
permission or made them a moderator of this specific channel), they should see that the message input box is disabled or they get an error message saying they don't have permission to post. - As Admin, go to
#astro-101-announcements
and post an announcement:Reminder: First assignment due next Friday!
This should work because admins can post in read-only channels.
- As
Part 5 Clean Up (Optional) You can keep these channels and the Team for further experimentation or delete them if desired. * To delete a channel (as Admin/Channel Owner): Channel Info -> Edit -> Delete. * To delete a Team (as Admin/Team Owner): Team Info -> Edit -> Delete Team.
Conclusion
In this workshop, you gained hands-on experience with key channel and discussion management features in Rocket.Chat. You created public and private channels, including a read-only channel, and organized them into a Team. You practiced using threaded discussions to keep conversations focused. Furthermore, you explored basic moderation actions like deleting messages and assigning channel-specific moderator roles, and observed how these roles affect user permissions. Effective use of these tools is vital for maintaining a structured, productive, and manageable communication environment within your Rocket.Chat workspace.
Integrations and Apps
One of Rocket.Chat's powerful aspects is its extensibility through integrations and apps. These allow you to connect Rocket.Chat with other tools and services your team uses, automate workflows, and add new functionalities directly within the chat interface. This can transform Rocket.Chat from a simple messaging tool into a central hub for team operations.
Rocket.Chat supports integrations in several ways: * Official Marketplace: A curated collection of apps developed by Rocket.Chat and third-party developers. * Webhooks (Incoming and Outgoing): A simple way to send or receive data between Rocket.Chat and other applications. * REST API & Realtime API: For deeper, custom integrations and bot development. * Bots: Automated users that can perform tasks, provide information, or interact with users and other services.
Understanding the Rocket.Chat Marketplace
The Rocket.Chat Marketplace is the easiest way to discover and install pre-built integrations and apps.
- Accessing the Marketplace:
- Log in as an administrator.
- Go to
Administration
->Workspace
->Marketplace
. - If your server is registered with Rocket.Chat Cloud (see Basic Installation -> Server Registration), you should be able to browse and install apps directly. If not registered, you might see a limited view or a prompt to register. Some apps might also be installable by downloading a package and uploading it manually, but the integrated marketplace is more convenient.
- Types of Apps:
- Connectors: Link Rocket.Chat to popular services like GitHub, GitLab, Jira, Trello, Google Calendar, Zoom, etc. These often provide notifications in Rocket.Chat channels based on events in the external service (e.g., new GitHub commit, Jira issue update).
- Productivity Tools: Apps for polls, reminders, RSS feeds, file sharing enhancements.
- Communication Enhancements: Apps for video conferencing (like Jitsi Meet integration if not using the built-in WebRTC), translation bots.
- Bots: Various specialized bots for different tasks.
- Installing an App:
- Find the app you want in the Marketplace.
- Click on it to see details, reviews, and installation instructions.
- Click the "Install" or "Get" button.
- You might need to agree to permissions the app requires.
- Once installed, the app may need further configuration (e.g., API keys for an external service, target channels for notifications). Configuration settings for installed apps are usually found in their own section within the Administration panel or under
Administration
->Settings
->Apps
.
- Managing Apps:
- From the Marketplace page, you can usually see your installed apps.
- You can enable/disable, update, configure, or uninstall apps from here or their respective settings pages.
- App Quality and Support:
- Apps in the marketplace can vary in quality and maintenance. Check reviews, last updated dates, and support information.
- Official apps by Rocket.Chat are generally well-supported. Third-party apps rely on their respective developers.
Installing and Configuring Common Apps (e.g., Jitsi, Webhooks)
Let's look at two common types of integrations: a video conferencing tool like Jitsi and the versatile Webhooks.
1. Jitsi Meet Integration (Video Conferencing)
Rocket.Chat has built-in WebRTC for basic audio/video calls. However, for more robust multi-party video conferencing, integrating with a dedicated service like Jitsi Meet is common. Jitsi Meet is an open-source video conferencing solution that you can self-host or use the public instance (meet.jit.si
).
- How it typically works:
Users can start a Jitsi video call directly from a Rocket.Chat channel or direct message. Rocket.Chat generates a unique Jitsi meeting URL and posts it in the chat. Users click the link to join the meeting in their browser or the Jitsi app. - Configuration (as Admin):
- Go to
Administration
->Settings
->Video Conference
. - Jitsi Section:
- Enable Jitsi: Set to
True
. - Jitsi Domain: Enter the domain of the Jitsi server you want to use.
- For the public Jitsi instance:
meet.jit.si
- If you self-host Jitsi:
your.jitsi.domain.com
- For the public Jitsi instance:
- Jitsi SSL: Ensure this is
True
if your Jitsi server uses HTTPS (which it should). - Jitsi Room Prefix (Optional): Add a prefix to Jitsi room names generated by Rocket.Chat (e.g.,
RocketChat-
). - Jitsi Chrome Extension (For screen sharing on some setups): ID of the Jitsi Chrome extension, usually pre-filled.
- Other options: Token authentication (if your Jitsi server is secured with JWT), default visibility, etc.
- Enable Jitsi: Set to
- Save changes.
- Go to
- Usage:
Once configured, users will see a video call icon (often a camera) in the message input area or channel header. Clicking it will start a Jitsi call.
2. Webhooks (Incoming and Outgoing)
Webhooks are a fundamental way for different web applications to communicate with each other in real-time. They allow you to send automated messages or data to other applications when something happens in Rocket.Chat, or receive messages/data from other applications to be posted in Rocket.Chat.
Incoming Webhooks
Allow external applications to send messages into Rocket.Chat channels.
- Use Cases:
- Notifications from CI/CD systems (Jenkins, GitLab CI, GitHub Actions) about build statuses.
- Alerts from monitoring systems (Prometheus Alertmanager, Nagios, Zabbix).
- Updates from project management tools (Jira, Trello) when tasks change.
- Custom scripts sending information to Rocket.Chat.
- How it Works:
- Admin/User creates an Incoming Webhook in Rocket.Chat:
- Go to
Administration
->Workspace
->Integrations
. - Click "New" and select "Incoming".
- Configuration:
- Name: A descriptive name (e.g.,
GitHub Commits
,Jenkins Builds
). - Post to Channel: Select the channel where messages from this webhook will be posted (e.g.,
#dev-ops
,#project-alpha
). You can also specify a user to post as, or allow the webhook to override the channel. - Post as: The username that will appear as the sender of these messages. This user must exist.
- Alias (Optional): A display name for the sender.
- Avatar URL (Optional): URL of an image to use as the avatar for these messages.
- Emoji (Optional): An emoji to use as the avatar.
- Script Enabled: If enabled, you can write JavaScript code to process the incoming payload before it's posted. This allows for complex transformations and formatting.
- Script (if enabled): The JavaScript code. The incoming payload is available as
request.content
. The script should return a JSON object representing the message to be posted (see Rocket.Chat message format documentation).
- Name: A descriptive name (e.g.,
- Go to
- Rocket.Chat generates a unique Webhook URL: This URL is secret. Anyone with this URL can post messages to the configured channel.
- Configure the External Application: In the external application (e.g., GitHub, Jenkins), configure it to send HTTP POST requests to this Webhook URL when an event occurs. The payload of the POST request is typically JSON.
- Admin/User creates an Incoming Webhook in Rocket.Chat:
- Payload Format:
- Rocket.Chat accepts various payload formats. A simple one is:
- Many services have specific payload structures. If "Script Enabled" is off, Rocket.Chat tries to parse common structures. If it's on, your script must handle the incoming
request.content
and produce a valid Rocket.Chat message object.
Outgoing Webhooks
Allow Rocket.Chat to send messages from Rocket.Chat channels to external applications when certain conditions are met.
- Use Cases:
- Triggering actions in external systems based on chat commands (e.g.,
!deploy production
posts to a deployment service). - Logging chat messages to an external auditing system.
- Creating a bot that listens to messages and responds by calling an external API.
- Triggering actions in external systems based on chat commands (e.g.,
-
How it Works:
- Admin/User creates an Outgoing Webhook in Rocket.Chat:
- Go to
Administration
->Workspace
->Integrations
. - Click "New" and select "Outgoing".
- Configuration:
- Name: A descriptive name.
- Channel (Optional): The specific channel(s) to listen to. If blank, listens to all public channels.
- Trigger Words (Optional): Specific words that, when they appear at the beginning of a message, trigger the webhook. If blank, all messages (matching other criteria) trigger it.
- Trigger Word Any Where in Message (Optional): If enabled, trigger words can appear anywhere in the message, not just at the start.
- Listen for Edits (Optional): Trigger webhook on message edits.
- Event Trigger (Important):
Message Sent
(default)User Joined Channel
User Left Channel
- And other events depending on Rocket.Chat version.
- Target User (Optional): Username whose messages will trigger this webhook.
- URLs: One or more URLs of external applications to which Rocket.Chat will send an HTTP POST request.
- Token (Optional): A secret token that Rocket.Chat will include in the payload. Your external application can verify this token to ensure the request genuinely came from your Rocket.Chat instance.
- Post as: User that the webhook posts as if it sends a response back to Rocket.Chat.
- Script Enabled / Script: Similar to incoming webhooks, allows processing the data before sending it to the external URL or processing the response from the external URL before posting it back to Rocket.Chat.
- Go to
- Rocket.Chat sends data: When a message matches the criteria, Rocket.Chat sends an HTTP POST request to the configured URL(s). The payload contains information about the message (sender, content, channel, timestamp, etc.).
- External Application processes the data: Your external application receives the POST request, processes the data, and can optionally send a response back to Rocket.Chat (if the webhook is configured to expect a response). This response can be a new message posted in the channel.
- Admin/User creates an Outgoing Webhook in Rocket.Chat:
-
Payload Sent by Rocket.Chat (Example for
Message Sent
event):{ "token": "YOUR_SECRET_TOKEN_IF_CONFIGURED", "channel_id": "GENERAL", "channel_name": "general", "message_id": "RandomMessageID", "timestamp": "2023-10-27T10:00:00.000Z", "user_id": "RandomUserID", "user_name": "testuser1", "text": "Hello from Rocket.Chat!", "trigger_word": "hello" // if configured and matched // ... other fields like attachments, edited_at, etc. }
- Responding to Outgoing Webhooks: If your external application sends a JSON response in the Rocket.Chat message format, Rocket.Chat can post it back to the original channel or as a DM to the user who triggered the webhook. Example response from your external service:
Webhooks are incredibly versatile. Incoming webhooks are great for getting notifications into Rocket.Chat. Outgoing webhooks are powerful for building bots or triggering external workflows from Rocket.Chat. When combined with scripting capabilities, they can handle very complex integration scenarios.
Workshop Setting Up an Incoming Webhook for Notifications
Objective
To create an incoming webhook in Rocket.Chat that allows an external service (simulated using curl
) to post messages to a specific channel. This demonstrates how you can receive notifications from other systems.
Prerequisites
- A running Rocket.Chat instance with administrator access.
- A user account with permission to manage integrations or admin access.
- A specific channel where notifications will be posted (e.g.,
#general
or create a new one like#alerts
). curl
command-line tool installed on your local machine or another server (to simulate the external service). Most Linux/macOS systems have it. For Windows, you can install it via Git Bash or use PowerShell'sInvoke-RestMethod
.
Scenario
We will create an incoming webhook that posts messages to a channel named #system-alerts
. We will then use curl
to send a simple JSON payload to this webhook's URL, simulating an alert from an external monitoring system.
Steps
1. Create a Dedicated Channel (Optional, Recommended)
If you don't have a suitable channel, let's create one for alerts.
- Log in to Rocket.Chat.
- Click the "Create" button (e.g.,
+
icon in the sidebar) -> "Channel". - Channel Name:
system-alerts
- Privacy: Public (or Private if only specific people should see alerts). Let's use Public for this workshop.
- Click "Create".
2. Navigate to Integrations
- As an administrator (or a user with appropriate permissions), click your avatar ->
Administration
. - In the Administration panel, search for
Integrations
or navigate toWorkspace
->Integrations
.
3. Create a New Incoming Webhook
- On the Integrations page, click the "New" button (top-right).
- Select "Incoming" from the type of integration.
4. Configure the Incoming Webhook
Fill in the details for your new webhook:
- Name:
External System Alerter
(A descriptive name for this webhook). - Enabled: Ensure this is set to
True
(toggle ON). - Post to Channel: Start typing the name of the channel where messages should be posted, e.g.,
#system-alerts
. Select it from the dropdown.- Note: You can also use
@username
to send a direct message to a user, or leave it to be specified in the payload if the webhook is configured to allow channel override (advanced).
- Note: You can also use
- Post as: Enter the username that will appear as the sender of messages from this webhook. This user must exist. For example, you could use your admin username or create a dedicated bot user (e.g.,
alerterbot
). Let's use your admin username for simplicity. - Alias (Optional): A display name that will override the "Post as" username. E.g.,
System Monitor
. - Avatar URL (Optional): URL to an image to be used as the avatar for messages from this webhook. You can find a generic alert icon online and use its URL. (e.g.,
https://i.imgur.com/wwSikDc.png
for a sample bell icon). - Emoji (Optional): An emoji to use as an avatar (e.g.,
:bell:
). This overrides Avatar URL if both are set. Let's try:rotating_light:
. - Script Enabled: Keep this
False
(toggle OFF) for this basic workshop. We'll send a simple payload that Rocket.Chat can understand directly. - Script: (Leave blank as Script Enabled is False).
- Respond to Sender (checkbox, if present): Usually for outgoing webhooks, might not be relevant here.
- Allow Unfinished Message (checkbox, if present): Leave as default.
5. Save and Get the Webhook URL
- Scroll down and click the "Save" button.
-
After saving, Rocket.Chat will display information about the webhook, including:
- Webhook URL: This is the unique URL that external services will use to send messages. It will look something like
https://chat.example.com/hooks/RANDOM_TOKEN/ANOTHER_RANDOM_TOKEN
. This URL is sensitive. Treat it like a password. - Token (sometimes shown separately): Part of the URL.
- Example Payloads: Rocket.Chat often shows examples of JSON payloads you can send.
- Webhook URL: This is the unique URL that external services will use to send messages. It will look something like
-
Important: Copy the Webhook URL and store it securely. You will need it in the next step.
6. Test the Webhook with curl
Now, we'll use curl
from your local machine's terminal (or another server) to simulate an external service sending a message to Rocket.Chat via the webhook.
Open your terminal.
-
Construct the
curl
command: ReplaceYOUR_WEBHOOK_URL
with the actual Webhook URL you copied. Replaceyour_server_ip
orchat.example.com
in the examples below with your actual Rocket.Chat URL if it's different in the webhook URL.Test 1: Simple Text Message
*curl -X POST \ -H 'Content-Type: application/json' \ --data '{"text": "Hello from curl! This is a test alert."}' \ YOUR_WEBHOOK_URL
curl
: The command-line tool. *-X POST
: Specifies the HTTP request method as POST. *-H 'Content-Type: application/json'
: Sets the Content-Type header to indicate that we are sending JSON data. *--data '{...}'
: Provides the JSON payload. The simplest payload just needs atext
field. *YOUR_WEBHOOK_URL
: The URL you copied from Rocket.Chat.Run this command.
-
Check Rocket.Chat: Go to the
#system-alerts
channel (or whichever channel you configured) in your Rocket.Chat client. You should see a new message:- Posted by the user you specified in "Post as" (or the Alias if you set one).
- With the avatar/emoji you set.
- Containing the text: "Hello from curl! This is a test alert."
If
curl
outputs{"success": true}
or similar, it means Rocket.Chat received and processed the request successfully. -
Test 2: Message with Attachments (More Advanced Alert) Let's send a slightly more complex message with an attachment, which is common for formatted alerts.
curl -X POST \ -H 'Content-Type: application/json' \ --data '{ "alias": "Critical System Alert", "emoji": ":fire:", "text": "A critical issue has been detected on Server X1!", "attachments": [ { "title": "CPU Usage Alert", "title_link": "http://your-monitoring-system.com/alerts/123", "text": "CPU utilization has exceeded 95% for the last 10 minutes.", "color": "#FF0000", "fields": [ { "title": "Severity", "value": "CRITICAL", "short": true }, { "title": "Hostname", "value": "server-x1.prod.example.com", "short": true } ], "ts": "'"$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")"'" } ] }' \ YOUR_WEBHOOK_URL
- We've added an
alias
andemoji
directly in the payload (these can override the webhook's default settings if the webhook is configured to allow it). - The
attachments
array allows for richer formatting. color
: Sets a color bar on the left of the attachment (e.g., red for critical).fields
: Allows displaying key-value pairs.ts
: Timestamp for the attachment. The$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")
part generates an ISO 8601 timestamp in UTC (this works on Linux/macOS; Windows PowerShell would use(Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
inside the JSON string). For simplicity you can also use a static timestamp string or omitts
.
Run this second
curl
command. - We've added an
-
Check Rocket.Chat Again: In the
#system-alerts
channel, you should see a new, more formatted message with a red color bar, title, link, and fields. This simulates a more detailed alert.
7. (Optional) Explore Scripting
If you wanted to transform an incoming payload that isn't in Rocket.Chat's expected format:
- Go back to
Administration
->Integrations
, edit yourExternal System Alerter
webhook. - Set Script Enabled to
True
(toggle ON). - In the Script field, you could add JavaScript. For example, if your external system sends
{"alert_message": "Something broke!", "level": "high"}
:class Script { process_incoming_request({ request }) { // request.content contains the raw payload from the POST request const payload = request.content; let messageColor = "#DDDDDD"; // Default color if (payload.level && payload.level.toLowerCase() === "high") { messageColor = "#FF0000"; // Red for high level } else if (payload.level && payload.level.toLowerCase() === "medium") { messageColor = "#FFA500"; // Orange for medium } return { content: { text: `Alert Received: ${payload.alert_message}`, attachments: [{ color: messageColor, text: `Severity: ${payload.level || 'Unknown'}` }] } }; } }
- Save changes.
- Now, if you send the custom payload with
curl
: The script would process this, and Rocket.Chat would post a formatted message based on the script's logic.
Conclusion
You have successfully created and tested an incoming webhook in Rocket.Chat. You learned how to configure it to post messages to a specific channel with a designated username and avatar/emoji. Using curl
, you simulated an external service sending both simple text messages and more complex, formatted messages with attachments. This powerful feature allows you to integrate a wide variety of external tools and services to send notifications and data directly into your Rocket.Chat workspace, centralizing information flow. You also got a glimpse of how scripting can further customize the handling of incoming webhook payloads.
API Usage Basics
Beyond webhooks, Rocket.Chat provides comprehensive REST and Realtime APIs that allow for much deeper and more programmatic interaction with the platform. These APIs can be used to:
- Build custom bots and integrations.
- Automate user management tasks (creating users, assigning roles).
- Manage channels and messages programmatically.
- Extract data from Rocket.Chat for reporting or analysis.
- Integrate Rocket.Chat into larger enterprise workflows.
1. REST API:
- The REST API allows you to perform actions by making standard HTTP requests (GET, POST, PUT, DELETE) to specific endpoints.
- Documentation: The official Rocket.Chat API documentation is your primary resource. It's usually available at
https://your.rocketchat.domain/api/v1/
(browse to this URL) or on the Rocket.Chat developer portal. - Endpoints: Cover virtually all aspects of Rocket.Chat, including:
- Authentication (
/login
,/me
) - Users (
/users.create
,/users.info
,/users.list
) - Channels (
/channels.create
,/channels.invite
,/channels.list
,/channels.history
) - Chat (
/chat.postMessage
,/chat.delete
,/chat.update
) - Settings (
/settings/:_id
) - And many more.
- Authentication (
- Authentication:
- To use the API, your client needs to authenticate with the Rocket.Chat server. This is typically done by sending a POST request to the
/api/v1/login
endpoint with a username and password (or LDAP credentials). - Upon successful login, the API returns an Auth Token (
X-Auth-Token
) and a User ID (X-User-Id
). - These two headers must be included in all subsequent API requests to authenticated endpoints.
- Personal Access Tokens (PATs): A more secure and convenient way for scripts or specific users to authenticate. Users can generate PATs from their "My Account" -> "Security" -> "Personal Access Tokens" section.
- When creating a PAT, you can give it a name and specify if it should bypass two-factor authentication (use with caution).
- The generated token acts as both the User ID and Auth Token when used in API headers (typically, you set
X-User-Id
to your user ID andX-Auth-Token
to the PAT, or sometimes just one header with the PAT depending on the context and Rocket.Chat version - check docs). - PATs are long-lived and should be treated like passwords. They can be revoked by the user at any time.
- To use the API, your client needs to authenticate with the Rocket.Chat server. This is typically done by sending a POST request to the
- Request/Response Format: Data is typically sent and received in JSON format.
2. Realtime API:
- The Realtime API allows you to subscribe to events happening in Rocket.Chat in real-time (e.g., new messages, user status changes) and send messages using a persistent WebSocket connection.
- It uses the DDP (Distributed Data Protocol), which is part of the Meteor framework that Rocket.Chat is built on.
- This is more complex to use directly than the REST API and is often used by client applications or sophisticated bots that need instant updates. Libraries exist in various programming languages (JavaScript, Python) to simplify DDP communication.
API Rate Limiting:
- To prevent abuse and ensure server stability, Rocket.Chat implements rate limiting on its API endpoints.
- Default limits are usually configurable by administrators (
Administration
->Settings
->General
->API Rate Limit
). - If you make too many requests in a short period, you'll receive an HTTP
429 Too Many Requests
error. Your application should handle this gracefully (e.g., by waiting and retrying with exponential backoff).
Common Tools for API Interaction:
curl
: A command-line tool for making HTTP requests. Useful for quick tests and scripting.- Postman / Insomnia: GUI tools for designing, building, testing, and documenting APIs. Highly recommended for exploring and working with REST APIs.
- Programming Language Libraries: Most languages have libraries for making HTTP requests (e.g.,
requests
in Python,axios
ornode-fetch
in JavaScript). For the Realtime API, specific DDP client libraries might be needed. Rocket.Chat also provides official SDKs (Software Development Kits) for some languages (e.g., JavaScript) that simplify API interaction.
Workshop Basic API Interaction with Rocket.Chat
Objective
To perform basic interactions with the Rocket.Chat REST API using curl
. This will involve authenticating, retrieving user information, and listing channels, demonstrating the fundamental principles of API usage. We will use Personal Access Tokens (PATs) for authentication as they are more suitable for scripting and direct API calls than username/password login for every request.
Prerequisites
- A running Rocket.Chat instance.
- Administrator access (or a regular user account for which you can generate a PAT).
curl
command-line tool installed.jq
command-line tool installed (optional but highly recommended for pretty-printing JSON responses in the terminal). You can install it on Ubuntu/Debian withsudo apt install jq
.
Steps
1. Enable API Access and Generate Personal Access Tokens (PATs)
-
Ensure API is Enabled (Admin Task):
- Log in as Admin.
- Go to
Administration
->Settings
->General
. - Scroll down to the "API" section.
- Ensure "Enable API" (or similar) is set to
True
. - (Optional) Review API rate limit settings.
-
Generate a Personal Access Token (as the user whose identity you want to use for API calls): For this workshop, you can do this for your admin account or a test user account. Let's use the admin account.
- Log in as the user for whom you want to generate the token (e.g., your admin user).
- Click your avatar (top-left) -> "My Account".
- In the "My Account" panel, select "Security" from the left sidebar.
- Find the "Personal Access Tokens" section.
- In the input field "New token name", enter a descriptive name for your token (e.g.,
My API Script
,Curl Test Token
). - Click the "Add" button.
- A dialog will appear showing your newly generated token. It will look something like
RANDOM_STRING_OF_CHARACTERS_AND_NUMBERS
. - Crucial: Copy this token immediately and store it in a secure place. You will only see it once. If you lose it, you'll have to generate a new one.
-
Note your User ID. It's usually displayed near your username or can be found by going to
Administration
->Users
, clicking your user, and checking the URL or info panel (or via an API call later). For example, if your admin username isadmin
, your User ID might also beadmin
or a random string likeabcdef12345
. Let's assume your User ID isYOUR_USER_ID
for now (you can find this from the Users admin page by clicking your user; it might be in the browser's address bar, or listed in the user info panel). -
Token Usage: This PAT will act as your
X-Auth-Token
. Your User ID will beX-User-Id
.
2. Understand API Endpoints and Authentication
- Base URL: All REST API v1 endpoints start with
https://your.rocketchat.domain/api/v1/
. Replaceyour.rocketchat.domain
with your Rocket.Chat server's URL (e.g.,https://chat.example.com/api/v1/
). - Headers for Authentication: For most API calls, you need to include:
X-Auth-Token: YOUR_PERSONAL_ACCESS_TOKEN
X-User-Id: YOUR_USER_ID
Content-Type: application/json
(especially for POST/PUT requests with a body).
3. Perform a Simple API Request (e.g., Get Current User Info) using curl
Let's test our PAT by fetching information about the currently authenticated user (which should be the user who owns the PAT).
- Open your terminal.
-
Set environment variables (optional but convenient): This makes the commands cleaner and avoids pasting sensitive tokens directly.
Remember to replace the placeholder values. -
API Call to
/api/v1/me
: This endpoint returns information about the user associated with the provided token.curl -s
: Runs curl in silent mode (no progress meter).-H "Header-Name: Value"
: Adds an HTTP header."$RC_URL/api/v1/me"
: The API endpoint URL, using our environment variable.| jq
: Pipes the JSON output tojq
for pretty-printing. If you don't havejq
, omit| jq
.
-
Expected Output (Example): You should see a JSON object containing details about your user account:
If you see{ "_id": "YOUR_USER_ID", "name": "Your Name", "username": "your_username", "status": "online", "active": true, "roles": [ "admin", // or other roles "user" ], "emails": [ { "address": "your.email@example.com", "verified": true } ], // ... other fields "success": true }
"success": true
and your user details, your PAT authentication is working! If you get an authentication error (e.g.,{"status": "error", "message": "You must be logged in to do this."}
or HTTP 401 Unauthorized), double-check yourRC_USER_ID
,RC_TOKEN
, andRC_URL
values.
4. Perform Another API Request (e.g., List Public Channels)
Let's try another endpoint: /api/v1/channels.list.joined
(to list channels the authenticated user has joined) or /api/v1/channels.list
(to list all public channels the user can see).
-
API Call to
/api/v1/channels.list.joined
: -
Expected Output (Example): A JSON object containing a list of channels.
This will list channels like{ "channels": [ { "_id": "GENERAL", "name": "general", "t": "c", // 'c' for channel "msgs": 123, // ... other channel details }, { "_id": "RandomChannelID1", "name": "astro-101-course", "t": "c", "teamMain": true, "teamId": "TeamIDHere", // ... }, { "_id": "RandomChannelID2", "name": "astro-101-announcements", "t": "c", "ro": true, // Read-only "teamId": "TeamIDHere", // ... } ], "count": 3, "offset": 0, "total": 3, "success": true }
#general
, any teams you're part of, and channels created in previous workshops that your user has joined.
5. Perform a POST Request (e.g., Post a Message to a Channel)
Now, let's try an action that modifies data: posting a message to a channel. We'll use the /api/v1/chat.postMessage
endpoint.
-
You need a
channelId
orroomId
. You can get this from the output ofchannels.list.joined
. For example, the#general
channel usually has_id: "GENERAL"
. Let's assume you want to post to#general
. You can also post by channel name usingroomName
butroomId
is usually preferred if known. If posting by name, the payload would be{"channel": "#general", "text": "Hello from API!"}
. ForroomId
, it's{"roomId": "GENERAL", "text": "Hello from API!"}
. -
API Call to
/api/v1/chat.postMessage
:curl -s -X POST \ -H "X-Auth-Token: $RC_TOKEN" \ -H "X-User-Id: $RC_USER_ID" \ -H "Content-Type: application/json" \ --data '{"roomId": "GENERAL", "text": "Hello from the Rocket.Chat API via curl! 🎉"}' \ "$RC_URL/api/v1/chat.postMessage" | jq
-X POST
: Specifies the POST method.-H "Content-Type: application/json"
: Indicates we're sending JSON.--data '{...}'
: The JSON payload. We're sending a message to the room with IDGENERAL
.
-
Check Rocket.Chat Client: Open your Rocket.Chat client and look at the
#general
channel. You should see a new message: "Hello from the Rocket.Chat API via curl! 🎉" posted by the user whose PAT you are using. -
Expected Output from
curl
(Example):{ "ts": 1667301234567, // Timestamp "channel": "GENERAL", "message": { "alias": "", "msg": "Hello from the Rocket.Chat API via curl! 🎉", "attachments": [], "parseUrls": true, "bot": null, "groupable": false, "tmid": null, "_updatedAt": "2023-10-27T12:00:00.000Z", "rid": "GENERAL", "u": { "_id": "YOUR_USER_ID", "username": "your_username", "name": "Your Name" }, "_id": "NewMessageID", "ts": "2023-10-27T12:00:00.000Z" }, "success": true }
6. (Optional) Use a REST Client (e.g., Postman)
For more complex API interactions or exploration, GUI tools like Postman are very helpful.
- Download and install Postman: postman.com/downloads/
- Create a new request in Postman:
- Method: GET
- URL:
https://your.rocketchat.domain/api/v1/me
- Headers Tab:
- Add
X-Auth-Token
with your PAT as the value. - Add
X-User-Id
with your User ID as the value.
- Add
- Click "Send".
- You should see the JSON response in Postman's response body section.
- You can save requests, organize them into collections, and easily try different endpoints and methods (POST, PUT, DELETE) with JSON bodies.
7. Revoke Personal Access Token (Good Practice After Testing)
If this token was just for testing, it's good practice to revoke it once you're done.
- In Rocket.Chat, go to "My Account" -> "Security" -> "Personal Access Tokens".
- Find the token you created (e.g.,
Curl Test Token
) in the list. - Click the "Revoke" button (often a trash can icon) next to it. Confirm.
- The token will no longer be valid for API authentication.
Conclusion
In this workshop, you learned the basics of interacting with the Rocket.Chat REST API. You successfully generated a Personal Access Token (PAT), used curl
to authenticate and make API calls to retrieve user information (/me
) and list joined channels (/channels.list.joined
), and performed a POST request to send a message (/chat.postMessage
).
Conclusion
In this workshop, you learned the basics of interacting with the Rocket.Chat REST API. You successfully generated a Personal Access Token (PAT), used curl
to authenticate and make API calls to retrieve user information (/me
), list joined channels (/channels.list.joined
), and performed a POST request to send a message (/chat.postMessage
). You saw how authentication works using headers (X-Auth-Token
, X-User-Id
) and how data is exchanged using JSON. While curl
is useful for testing and simple scripts, more complex integrations would typically use dedicated HTTP libraries or Rocket.Chat SDKs available for various programming languages. This foundational understanding of the REST API opens the door to automating tasks, building custom bots, and deeply integrating Rocket.Chat with your other tools and workflows. Remember to consult the official Rocket.Chat API documentation for details on all available endpoints and their parameters.
3. Advanced Configuration and Scaling
This section delves into more complex configurations, performance optimization, and strategies for scaling your Rocket.Chat instance to handle a larger user base and higher load. Topics include high availability setups, database optimization, performance tuning, monitoring, and advanced troubleshooting. These are typically relevant for larger deployments or production environments requiring high levels of reliability and performance.
High Availability (HA) and Load Balancing
For critical deployments where downtime is unacceptable, setting up a High Availability (HA) architecture is essential. This involves eliminating single points of failure by running multiple instances of Rocket.Chat and its dependencies (like MongoDB) and using a load balancer to distribute traffic among them.
Running Multiple Rocket.Chat Instances
The core idea is to run two or more identical Rocket.Chat application instances simultaneously. If one instance fails or needs maintenance, the others can continue serving user requests.
- Prerequisites:
- Shared Database: All Rocket.Chat instances must connect to the same MongoDB replica set. This ensures data consistency.
- Shared File Storage (Optional but Recommended): If using local filesystem storage for uploads (
FileSystem
option), all instances need access to the same shared storage (e.g., NFS, GlusterFS) mounted at the same path (e.g.,/app/uploads
inside the containers). Alternatively, use a centralized object storage solution like MinIO or AWS S3, which avoids the need for shared filesystem mounts. - Load Balancer: A mechanism to distribute incoming user traffic across the available Rocket.Chat instances.
- How it Works with Docker Compose (Simple Horizontal Scaling on One Host):
You can scale the
rocketchat
service directly within Docker Compose on a single powerful host: This command tells Docker Compose to start 3 instances (containers) of therocketchat
service defined in yourdocker-compose.yml
. Docker Compose's built-in networking will handle basic round-robin load balancing between these containers if accessed directly via the host port, but this is usually not sufficient or recommended for production HA. A dedicated load balancer is preferred. - Multi-Host Deployment (Docker Swarm / Kubernetes):
For true HA across multiple servers, container orchestration platforms are typically used:
- Docker Swarm: Docker's native clustering and orchestration tool. You define your Rocket.Chat stack (including MongoDB replica set, Rocket.Chat service, load balancer/reverse proxy like Traefik) as a Swarm service and deploy it across multiple "nodes" (servers) in the Swarm cluster. Swarm handles service discovery, scaling, and rescheduling containers if a node fails.
- Kubernetes (K8s): The industry standard for container orchestration. Deploying Rocket.Chat on Kubernetes involves creating Deployment objects for the Rocket.Chat app, a StatefulSet for the MongoDB replica set, Services for internal communication, and an Ingress controller (like Nginx Ingress or Traefik) to manage external access and load balancing. Kubernetes offers sophisticated scheduling, scaling, self-healing, and configuration management capabilities but has a steeper learning curve.
- Instance Preferences (Event Broadcasting):
When running multiple instances, Rocket.Chat needs an efficient way to broadcast events (like new messages, presence updates) between instances. This ensures all users see updates in real-time, regardless of which instance they are connected to.
- Location:
Administration
->Settings
->General
->Instance Preferences
(or similar) - Enable Instance Sync: Set to
True
. - Broadcasting Method: Rocket.Chat uses the MongoDB oplog by default (requires replica set) or can be configured to use Redis Pub/Sub for potentially better performance at scale. Using Redis requires setting up a Redis instance and configuring Rocket.Chat to connect to it.
- Location:
Setting Up a MongoDB Replica Set
A single MongoDB instance is a single point of failure. A replica set provides redundancy and high availability for your database.
* Concept: A replica set is a group of MongoDB servers (mongod
processes) that maintain the same data set.
* Primary: One member acts as the primary node. It receives all write operations. Clients typically connect to the primary for reads as well, by default.
* Secondaries: One or more secondary nodes replicate the primary's oplog (log of operations) and apply the changes to their own data sets asynchronously. Secondaries can handle read operations (if configured), providing read scaling.
* Arbiter (Optional): A lightweight mongod
process that participates in elections for primary but does not hold data. Useful for achieving a majority in replica sets with an even number of data-bearing nodes (e.g., 2 data nodes + 1 arbiter). A replica set needs a majority of nodes to be available to elect a primary and remain writable. A typical minimum HA setup is 3 data-bearing nodes (1 Primary, 2 Secondaries).
* Automatic Failover: If the primary node becomes unavailable, the remaining secondaries hold an election to choose a new primary from among themselves. This process usually takes a few seconds, ensuring minimal downtime for write operations. Rocket.Chat's MongoDB driver will automatically detect the new primary and redirect connections.
* Our Basic Docker Setup: The docker-compose.yml
we created earlier (command: mongod --replSet rs0 ...
) starts MongoDB in replica set mode (rs0
), but only with one member. This is sufficient for enabling the oplog features Rocket.Chat needs, but it doesn't provide HA.
* Creating a Multi-Node Replica Set:
* With Docker Compose (on one host, for testing HA concepts): You could define multiple mongo
services (mongo1
, mongo2
, mongo3
) in the docker-compose.yml
, each with its own data volume, and configure them to form a replica set. This isn't true HA as they are all on the same host.
* With Docker Swarm/Kubernetes (Recommended): Deploy MongoDB as a StatefulSet (in K8s) or a service with volume constraints (in Swarm) across multiple nodes. You'd typically start one instance, initiate the replica set (rs.initiate()
), and then add the other instances as members (rs.add()
). The MongoDB connection string in Rocket.Chat's environment variables needs to list multiple members of the replica set:
MONGO_URL=mongodb://mongo1:27017,mongo2:27017,mongo3:27017/rocketchat?replicaSet=rs0
MONGO_OPLOG_URL=mongodb://mongo1:27017,mongo2:27017,mongo3:27017/local?replicaSet=rs0
mongo1
, mongo2
, mongo3
with the actual hostnames/service names of your MongoDB instances. The driver will automatically connect to the current primary.
* Manual Setup: You can install MongoDB directly on multiple servers and configure the replica set manually via the mongosh
shell.
Load Balancer Configuration (Nginx Example)
A load balancer distributes incoming connections across your multiple healthy Rocket.Chat instances. Nginx can act as an effective load balancer.
- Modify Nginx Upstream Block:
In your Nginx configuration file (e.g.,
/etc/nginx/sites-available/rocketchat
), modify theupstream
block to include the IP addresses (or resolvable hostnames) and ports of all your running Rocket.Chat instances.upstream rocketchat_servers { # Renamed for clarity # Least Connections balances based on active connections - good for WebSockets least_conn; # List your Rocket.Chat instances server <IP_Address_Instance_1>:3000; server <IP_Address_Instance_2>:3000; server <IP_Address_Instance_3>:3000; # Add more servers as needed # Sticky sessions (Optional but often needed for WebSocket stability without Redis broadcasting) # Use ip_hash to ensure a client always connects to the same backend server # ip_hash; # Note: ip_hash can lead to uneven load if IPs are not well distributed. # If using Redis for broadcasting, sticky sessions might not be strictly necessary, # allowing for better load distribution with least_conn or round_robin. } server { # ... (listen directives, server_name, ssl settings) ... location / { proxy_pass http://rocketchat_servers; # Pass to the upstream group # ... (All other proxy_set_header directives remain the same) ... proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # ... (timeouts, buffering off) ... } }
- Load Balancing Algorithms:
round_robin
(Default): Distributes requests sequentially across servers. Simple but doesn't account for server load.least_conn
: Sends requests to the server with the fewest active connections. Generally better for long-lived connections like WebSockets.ip_hash
: Ensures requests from the same client IP address always go to the same server. This provides session persistence ("sticky sessions") which can be important if Rocket.Chat instances don't share session state perfectly (e.g., if not using Redis broadcast). However, it can lead to uneven load distribution.
- Health Checks (Recommended):
Nginx can perform active health checks to automatically remove unresponsive Rocket.Chat instances from the load balancing pool. This requires Nginx Plus (paid) or using third-party modules/setups. Basic Nginx open-source marks a server as down after failed connection attempts (
max_fails
,fail_timeout
parameters in theserver
directive within the upstream block), but doesn't actively probe. - External Load Balancers: Cloud providers (AWS ELB, Google Cloud Load Balancer, Azure Load Balancer) offer managed load balancing services that handle scaling, health checks, and SSL termination. Dedicated hardware load balancers (like F5) or software like HAProxy are also options.
Implementing HA requires careful planning of your infrastructure (multiple servers, networking), database replication, shared storage or object storage, and load balancing strategy. Container orchestrators like Kubernetes significantly simplify managing such deployments.
Workshop Conceptualizing an HA Setup
Objective
To understand the key components required for a High Availability Rocket.Chat setup and how they interact, without actually deploying multiple servers (as that requires significant infrastructure). We will modify the Nginx configuration conceptually and discuss the role of the MongoDB replica set and instance communication.
Prerequisites
- A running Rocket.Chat instance with Nginx reverse proxy (from previous workshops).
- Understanding of the concepts: multiple instances, load balancing, MongoDB replica sets.
Steps
1. Review Current Single-Instance Setup
- Look at your
docker-compose.yml
. You have onerocketchat
service and onemongo
service (running with--replSet rs0
). - Look at your
/etc/nginx/sites-available/rocketchat
file. Theupstream
block points to a single backend (127.0.0.1:3000
).
2. Conceptualize Running Multiple Instances
- Imagine you have two additional servers (Server B, Server C) besides your current server (Server A).
- You would deploy the same Rocket.Chat Docker image on Server B and Server C.
- Crucially: These instances on Server B and C must be configured (via
MONGO_URL
,MONGO_OPLOG_URL
environment variables) to connect to the same MongoDB database used by Server A.
3. Conceptualize the MongoDB Replica Set
- The single
mongo
instance on Server A (started with--replSet rs0
) is not highly available. - For HA, you would need at least two more MongoDB instances, ideally running on separate servers (perhaps Server B and Server C, or dedicated database servers).
- Let's say you have
mongoA
on Server A,mongoB
on Server B,mongoC
on Server C. - You would initiate the replica set on
mongoA
:rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "mongoA_ip:27017" }] })
. - Then add the other members:
rs.add("mongoB_ip:27017")
,rs.add("mongoC_ip:27017")
. - One instance becomes Primary, the others Secondaries. They replicate data.
- The
MONGO_URL
for all Rocket.Chat instances (on Servers A, B, C) would be updated to include all members:MONGO_URL=mongodb://mongoA_ip:27017,mongoB_ip:27017,mongoC_ip:27017/rocketchat?replicaSet=rs0
4. Conceptualize Load Balancing with Nginx
- Assume your Nginx reverse proxy runs on Server A (or a dedicated load balancer server).
- We need to tell Nginx about the Rocket.Chat instances running on Servers A, B, and C.
-
Edit the Nginx configuration (
sudo nano /etc/nginx/sites-available/rocketchat
): Modify theupstream
block:# Upstream group for multiple Rocket.Chat instances upstream rocketchat_servers { # Use least_conn for better WebSocket distribution least_conn; # Instance on Server A (replace with actual internal IP if Nginx is separate) server 127.0.0.1:3000 max_fails=3 fail_timeout=15s; # Instance on Server B (replace with Server B's IP) server 192.168.1.101:3000 max_fails=3 fail_timeout=15s; # Instance on Server C (replace with Server C's IP) server 192.168.1.102:3000 max_fails=3 fail_timeout=15s; # Consider ip_hash if sticky sessions are needed and Redis broadcast is not used # ip_hash; } server { # ... listen, server_name, ssl settings ... location / { proxy_pass http://rocketchat_servers; # Point to the upstream group # ... ALL other proxy settings remain the same (Headers, WebSocket support, etc.) ... } }
- We added the (hypothetical) IPs of the Rocket.Chat instances on Server B (
192.168.1.101
) and Server C (192.168.1.102
). - We switched to
least_conn
load balancing. - We added
max_fails=3 fail_timeout=15s
so Nginx will temporarily stop sending traffic to an instance if it fails to connect 3 times within 15 seconds. - We updated the
proxy_pass
directive to use the new upstream group namerocketchat_servers
.
- We added the (hypothetical) IPs of the Rocket.Chat instances on Server B (
-
Test and Reload Nginx:
Now, Nginx would distribute incoming requests across the three (conceptual) Rocket.Chat instances.
5. Configure Instance Communication (Event Broadcasting)
- For real-time events (new messages, presence) to work seamlessly across all instances connected via the load balancer, configure instance communication:
- Log in as Admin to Rocket.Chat (you'll hit one of the instances via Nginx).
- Go to
Administration
->Settings
->General
->Instance Preferences
. - Ensure "Enable Instance Sync" is
True
. - Broadcasting Method:
- MongoDB Oplog (Default): This works out-of-the-box if your
MONGO_URL
andMONGO_OPLOG_URL
point to the replica set. Each instance tails the MongoDB oplog to see changes made by other instances. - Redis: If you set up a Redis server (or cluster), you can change the method to
Redis
, and provide the Redis host, port, and password. This can sometimes offer better performance for broadcasting at very large scale compared to tailing the oplog.
- MongoDB Oplog (Default): This works out-of-the-box if your
6. Shared Storage Considerations (File Uploads)
- If using the default
FileSystem
storage for uploads:- The directory specified in
Administration
->Settings
->File Upload
->Storage Type
->FileSystem Path
(e.g.,/app/uploads
inside the container) must point to the same shared location for all Rocket.Chat instances (A, B, C). - This could be an NFS mount, GlusterFS volume, etc., mounted into each container at
/app/uploads
.
- The directory specified in
- Alternative: Object Storage (Recommended for HA/Scaling):
- Configure Rocket.Chat to use Amazon S3, Google Cloud Storage, or a self-hosted S3-compatible solution like MinIO.
- Go to
Administration
->Settings
->File Upload
. - Change
Storage Type
toAmazonS3
orGoogleCloudStorage
orMinio
. - Configure the bucket name, region, access keys, etc.
- With object storage, instances don't need shared local filesystem mounts for uploads, simplifying the setup.
Conclusion
This conceptual workshop outlined the essential components for a highly available Rocket.Chat deployment. It involves running multiple Rocket.Chat application instances, ensuring they connect to a resilient MongoDB replica set, using a load balancer (like Nginx) to distribute traffic and handle failures, enabling instance communication for real-time event synchronization, and implementing a shared or centralized storage solution for file uploads. While we didn't build the multi-server infrastructure, understanding how these pieces fit together is crucial for planning and implementing a scalable and reliable Rocket.Chat service using tools like Docker Swarm or Kubernetes in a real-world scenario.
Database Optimization and Maintenance
MongoDB is the heart of Rocket.Chat, storing all messages, user data, settings, and more. The performance and health of your MongoDB instance(s) directly impact the overall responsiveness and reliability of Rocket.Chat. Optimization and regular maintenance are crucial, especially as your data grows.
Indexing Strategy
Indexes are special data structures in MongoDB that store a small portion of the collection's data set in an easy-to-traverse form. They allow MongoDB to execute queries much faster by avoiding scanning every document in a collection.
- Rocket.Chat's Default Indexes: Rocket.Chat automatically creates several indexes on its collections (e.g., on
rocketchat_message
forrid
,ts
; onusers
forusername
,emails.address
, etc.) during startup and migrations. These cover most common query patterns. - Verifying Indexes: You can check existing indexes using the
mongosh
shell: - Custom Indexes: In rare cases, if you identify specific slow queries (e.g., through profiling or monitoring) related to custom integrations or unique usage patterns, you might consider adding custom indexes. However, do this with caution:
- Indexes consume RAM and disk space.
- They slow down write operations (inserts, updates, deletes) because the index must also be updated.
- Poorly designed indexes can actually hurt performance.
- Always test the impact of adding new indexes in a staging environment.
- Creating indexes on large collections can be resource-intensive and lock the collection temporarily. Plan for background index builds (
{ background: true }
option increateIndex
).
- Monitoring Index Usage: MongoDB tracks index usage statistics. You can use
$indexStats
aggregation pipeline stage to see how often indexes are used, which can help identify unused or inefficient indexes. - Dropping Indexes: If you identify unused indexes (especially custom ones you added), dropping them can save resources. Be very careful not to drop essential indexes used by Rocket.Chat core.
General Strategy: Rely on Rocket.Chat's default indexes. Monitor for slow queries. Only add custom indexes after careful analysis and testing. Ensure indexes fit in RAM for best performance.
Storage Engine (WiredTiger)
MongoDB supports different storage engines. WiredTiger is the default storage engine for modern MongoDB versions (since 3.2) and is generally recommended for most workloads, including Rocket.Chat.
- Features:
- Document-Level Concurrency: Allows multiple clients to modify different documents in a collection simultaneously, improving performance for concurrent workloads.
- Compression: Supports compression for data and indexes (e.g.,
snappy
default,zlib
,zstd
), reducing disk space usage and potentially improving I/O performance. Rocket.Chat collections benefit significantly from compression. - Caching: WiredTiger uses both the filesystem cache (managed by the OS) and its own internal cache. Properly sizing the WiredTiger internal cache (
storage.wiredTiger.engineConfig.cacheSizeGB
inmongod.conf
or--wiredTigerCacheSizeGB
command-line option) is critical for performance. It should generally be large enough to hold the working set (frequently accessed data and indexes) but leave enough RAM for the OS filesystem cache and other processes (like Rocket.Chat itself if on the same server). A common recommendation is 50-60% of system RAM minus 1GB, allocated to WiredTiger cache, assuming MongoDB is the primary workload on the server. - Checkpoints: Periodically writes snapshot data to disk, providing durability.
- Configuration: WiredTiger settings are usually configured in the MongoDB configuration file (
mongod.conf
) or via command-line options. Our basic Docker setup doesn't explicitly configure a cache size, letting MongoDB use a default (often a fraction of host RAM). For production, tuning thewiredTigerCacheSizeGB
is important.
Regular Maintenance Tasks
- Backups: Absolutely essential. Implement a regular backup strategy for your MongoDB database. Options include:
mongodump
: A command-line utility that produces a binary export of the database content. Good for logical backups. Can be resource-intensive on a live primary; consider running it on a secondary node in a replica set.- Filesystem Snapshots: If using LVM or specific filesystem/cloud provider snapshots, you can take point-in-time snapshots of the MongoDB data files (requires journaling enabled, which is default). Ensure data consistency by freezing writes briefly or taking snapshots on a secondary.
- MongoDB Cloud Manager / Ops Manager (Enterprise): Offer managed backup solutions.
- Cloud Provider Backups: Managed database services (like MongoDB Atlas, AWS DocumentDB) often have built-in backup features.
- Testing: Regularly test your backup restoration process! Backups are useless if they cannot be restored correctly.
- Monitoring: Monitor key MongoDB metrics:
- Performance: Query latency, operation counts (reads, writes, commands), connections, cache usage (hit rate, eviction), lock contention, network traffic.
- Resource Usage: CPU, RAM (especially WiredTiger cache and system memory), disk I/O, disk space.
- Replication: Replica set status (
rs.status()
), replication lag (replicationLag
), oplog window size (oplog window
). The oplog window indicates how far back in time a secondary can be before needing a full resync if it falls behind. Ensure it's large enough to cover expected maintenance periods or network interruptions. AdjustoplogSizeMB
if needed (requires careful planning, often a restart). - Tools: MongoDB commands (
db.serverStatus()
,db.stats()
,rs.status()
), MongoDB Cloud Manager/Ops Manager, Prometheus with MongoDB Exporter, Datadog, Netdata, etc.
- Compact / Repair (Use with Caution):
compact
command: Rewrites collections and indexes to reclaim disk space lost due to data fragmentation (updates, deletes). Can be resource-intensive and block operations. Usually better handled by WiredTiger's mechanisms automatically, but might be needed in specific scenarios with heavy delete/update workloads. Run on secondaries first.repairDatabase
command: Checks for and attempts to repair corrupted data files. Requires significant disk space and downtime. Primarily a last resort for data recovery. Regular backups are the preferred strategy.
- Log Rotation: Ensure MongoDB logs (
mongod.log
) are rotated regularly to prevent them from consuming excessive disk space. MongoDB has built-in log rotation capabilities (systemLog.logRotate
option) or use external tools like Linuxlogrotate
. - Upgrades: Plan and test MongoDB version upgrades carefully. Read the release notes for backward-incompatible changes or specific upgrade procedures. Upgrade secondary nodes before the primary in a replica set to minimize downtime. Ensure Rocket.Chat supports the target MongoDB version.
Data Pruning and Archiving
As a chat application runs, its database grows continuously. Unmanaged growth can lead to performance degradation and increased storage costs. Rocket.Chat provides tools for pruning old data.
- Automatic Pruning:
- Location:
Administration
->Workspace
->Settings
->Retention Policy
. - Enable Retention Policy: Toggle to enable global pruning rules.
- Granularity: Configure separate retention periods for:
- Public Channels
- Private Channels
- Direct Messages (DMs)
- Direct Messages with Multiple Users
- Retention Period: Specify the maximum age of messages to keep (e.g., "Delete messages older than 30 days").
- File Retention: Choose whether to also prune files associated with the deleted messages.
- Advanced: Exclude specific channels from the global policy (e.g., keep
#legal
messages forever). Set per-channel retention overrides. Specify precise times for the pruning background job to run.
- Location:
- Manual Pruning:
- Location:
Administration
->Workspace
->Rooms
. - Select a specific channel/room.
- Use the "Prune Messages" option (often under the three-dots menu or an Actions button).
- Allows deleting messages older than a specified date, newer than a specified date, or between dates. Can also specify users whose messages should be pruned.
- Use with extreme caution. Manual pruning is irreversible.
- Location:
- Archiving: Rocket.Chat itself doesn't have a built-in "archive to cold storage" feature. Pruning means deletion. If you need to archive messages for compliance or historical purposes before pruning, you would typically need to:
- Use the REST API to export messages from specific channels or date ranges.
- Perform a
mongodump
before pruning. - Store the exported data or dump files in a separate, long-term storage system.
Regular database maintenance, appropriate indexing, performance monitoring, and a sensible data retention strategy are essential for keeping your Rocket.Chat instance running smoothly over the long term.
Workshop Monitoring MongoDB and Basic Maintenance
Objective
To use mongosh
commands and potentially server monitoring tools (like htop
) to inspect the status of your MongoDB instance, check index usage, and understand resource consumption. We will also simulate enabling a basic retention policy in Rocket.Chat.
Prerequisites
- A running Rocket.Chat instance using the Docker Compose setup.
- Access to the server terminal where Docker is running.
mongosh
accessible within the MongoDB container (docker compose exec mongo mongosh
).- (Optional)
htop
installed on the host server (sudo apt install htop
). - Administrator access to Rocket.Chat UI.
Steps
1. Connect to MongoDB Shell
You are now inside the MongoDB shell, connected to yourmongod
instance.
2. Check Database Status
The db.serverStatus()
command provides a wealth of information.
// Ensure you are using the admin database context for some server-wide commands,
// though many stats are available from any db context.
use admin
// Get comprehensive server status (output is long!)
db.serverStatus()
host
, version
, process
, pid
, uptime
* connections
: Shows current
, available
. High current connections might indicate load.
* network
: Bytes in/out, number of requests.
* opcounters
: Counts of insert, query, update, delete, command operations. Useful for understanding workload type.
* locks
: Indicates database or collection lock contention (high values might indicate performance bottlenecks).
* wiredTiger
: Contains detailed stats about the storage engine:
* cache
: Look for bytes currently in the cache
, pages read into cache
, pages written from cache
. A high read rate might mean your cache isn't large enough for your working set.
* concurrentTransactions
: Information about read/write tickets available/used.
* mem
: Memory usage (resident
, virtual
).
* Get Database Statistics: Switch to the Rocket.Chat database and check its size.
3. Inspect Indexes Check the indexes on the primary message collection.
* Observe the default indexes created by Rocket.Chat (e.g., onrid
, ts
, u._id
, editedAt
, tmid
). Note their names and the fields they cover.
* Simulate Checking Index Usage (Note: Needs activity to show stats)
On a busy server, $indexStats
shows usage. On a newly created or idle server, stats might be zero.
Look at the accesses.ops
field for each index. A high number indicates frequent use. Zero might indicate an unused index (but be careful, it might be used for infrequent but important queries).
4. Monitor Resource Usage (Host Level)
* Exit mongosh
: Type exit
and press Enter.
* Use docker stats
: This shows real-time resource usage (CPU %, Mem Usage/Limit, Net I/O, Block I/O) for your running containers.
mongo
and rocketchat
containers. Press Ctrl+C
to exit.
* (Optional) Use htop
on the host:
* Press F4
(Filter) and type docker
or mongo
or node
to filter processes.
* Observe the CPU% and MEM% used by the mongod
process (running inside the container, but visible on the host) and the Node.js processes for Rocket.Chat.
* Look at overall system Memory usage (top bar). Is there free memory? Is swapping occurring (indicated by Swp
usage)? High swap usage drastically impacts performance.
* Press F10
or q
to quit htop
.
5. Simulate Enabling Retention Policy (in Rocket.Chat UI) Let's configure Rocket.Chat to automatically delete old messages.
- Log in as Admin to Rocket.Chat UI.
- Go to
Administration
->Workspace
->Settings
->Retention Policy
. - Enable Global Policy: Set
Enable Retention Policy
toTrue
(toggle ON). - Configure Policy:
Global Maximum Message Age (in days)
: Set this to a value, e.g.,365
(keep messages for 1 year).Apply to channels
: SetPublic Channels
toTrue
. SetPrivate Channels
toTrue
. SetDirect Messages
toTrue
. SetDirect Messages with Multiple Users
toTrue
.Maximum message age in days per type
: You can override the global setting here if needed. Let's keep them blank to use the global 365 days.Files Retention
: ChoosePrune Files Only When All Messages Are Removed
orKeep Files
. For this test, selectKeep Files
.Advanced Pruning Schedule
: Leave this as default (runs daily at a specified time).
-
Save Changes: Click "Save changes".
-
Observation: You won't see immediate deletion unless you have messages older than 365 days. This background task runs periodically (as configured in the schedule). For a real deployment, you would monitor logs or database size over time to confirm pruning is working as expected after the scheduled run time. You might also see related messages in
Administration
->View Logs
.
6. Review Oplog Size (Replica Set Context) Even though we have a single-node replica set, we can check the configured oplog size.
docker compose exec mongo mongosh
use local // Switch to the 'local' database where oplog resides
// Show oplog status, including max size and time window
rs.printReplicationInfo()
// or
db.oplog.rs.stats() // More detailed stats if oplog is large enough
configured oplog size
and oplog window
. The window shows how much time the oplog covers. A larger window provides more resilience against secondaries falling behind but requires more disk space. The oplogSize
was set to 128MB in our docker-compose.yml
.
7. Exit mongosh
Type exit
.
Conclusion
In this workshop, you practiced essential MongoDB monitoring and maintenance tasks within the context of your Rocket.Chat deployment. You used mongosh
to check server status (db.serverStatus()
), database statistics (db.stats()
), and review index configurations (db.rocketchat_message.getIndexes()
). You also learned how to monitor container resource usage with docker stats
and conceptually check host resource usage with htop
. Finally, you simulated enabling Rocket.Chat's built-in message retention policy to manage database growth over time. Regularly performing these checks and implementing appropriate retention policies are vital for maintaining a healthy and performant MongoDB backend for your Rocket.Chat instance.
Performance Tuning and Monitoring
Ensuring your Rocket.Chat instance performs well under load requires ongoing monitoring and potentially tuning various components, from the application itself to the underlying database and server infrastructure.
Identifying Bottlenecks (APM, Logging, Metrics)
The first step in tuning is identifying where performance issues lie. Common bottlenecks include CPU, RAM, Disk I/O, Network latency, database queries, or specific application logic.
- Application Performance Monitoring (APM):
- APM tools provide deep insights into your application's behavior, tracing requests as they flow through different components, measuring execution times of functions and database queries, and highlighting errors or slow transactions.
- Rocket.Chat APM Integration: Rocket.Chat has built-in support for integrating with APM services that follow the OpenTelemetry standard or specific providers.
- Configuration:
Administration
->Settings
->APM
. Enable it and configure the connection details for your chosen APM service (e.g., Datadog, Elastic APM, Dynatrace, New Relic, or a self-hosted solution like Jaeger or Signoz). - Benefits: Pinpoint slow API endpoints, identify inefficient application code, trace distributed requests across multiple services (if applicable), visualize performance trends.
- Rocket.Chat Logs:
- The application logs can reveal errors, warnings, and sometimes performance-related information.
- Location: Viewable in the UI (
Administration
->Workspace
->View Logs
) or directly from the Docker container logs (docker compose logs -f rocketchat
). - Log Level: Adjust the log verbosity in
Administration
->Settings
->Logs
(Log Level
: 0=Debug, 1=Info, 2=Warn, 3=Error). Debug level provides the most detail but can impact performance and generate large logs. Use it temporarily for troubleshooting specific issues.
- System Metrics (Host and Container):
- Monitor basic system resources: CPU usage (per core and overall), RAM usage (total, used, free, cached, swap), Disk I/O (read/write rates, wait times), Disk Space usage, Network traffic (bandwidth, packets, errors).
- Tools:
htop
,vmstat
,iostat
,df
,iftop
,docker stats
. - Monitoring Systems: Set up a dedicated monitoring system like Prometheus with Grafana, Zabbix, Nagios, or Datadog. Use exporters like
node_exporter
(for host metrics),cadvisor
(for container metrics), andmongodb_exporter
(for MongoDB metrics) to feed data into Prometheus. Grafana can then be used to create dashboards visualizing these metrics over time.
- MongoDB Monitoring:
- As discussed previously, monitor MongoDB-specific metrics (connections, opcounters, cache performance, replication lag, locks) using
db.serverStatus()
,rs.status()
, and tools likemongodb_exporter
. Slow MongoDB queries are a very common cause of poor Rocket.Chat performance. Use the database profiler (db.setProfilingLevel()
) to identify slow operations.
- As discussed previously, monitor MongoDB-specific metrics (connections, opcounters, cache performance, replication lag, locks) using
- Browser Developer Tools (Client-Side Performance):
- Use your browser's developer tools (F12) to analyze client-side performance. The "Network" tab shows loading times for all assets (JS, CSS, images, API calls). The "Performance" tab can help diagnose slow JavaScript execution or rendering issues on the client side. Slow client performance can be perceived as server slowness.
Tuning Node.js and Rocket.Chat Settings
- Node.js Options:
- You can pass Node.js runtime options to the Rocket.Chat process via the
NODE_OPTIONS
environment variable in yourdocker-compose.yml
. - Memory Limit (
--max-old-space-size
): Controls the maximum size of Node.js's main memory heap (where JavaScript objects are stored). If your Rocket.Chat container is crashing with out-of-memory errors, or if you have ample RAM, you might increase this. E.g.,NODE_OPTIONS=--max-old-space-size=4096
(sets heap size to 4GB). Set this carefully based on available container/system RAM, leaving room for other processes and caches. - Garbage Collection Tuning (Advanced): Other flags can influence garbage collection behavior, but defaults are usually reasonable. Tuning GC requires deep understanding.
- You can pass Node.js runtime options to the Rocket.Chat process via the
- Rocket.Chat Instance Scaling: Running multiple instances behind a load balancer (as discussed in HA) is the primary way to scale the application layer horizontally.
- WebSocket Connections: Rocket.Chat relies heavily on WebSockets. Ensure your reverse proxy (Nginx) is correctly configured for WebSocket proxying (
Upgrade
andConnection
headers) and has appropriate timeouts (proxy_read_timeout
). - Specific Rocket.Chat Settings:
- File Upload Limits: Setting excessively high file upload limits (
Administration
->Settings
->File Upload
->Maximum File Size
) can strain server resources if many large files are uploaded concurrently. - Message Load Limits: Settings related to how many messages are loaded initially (
Accounts
->Default User Preferences
->Unread Count
) can affect initial load times for users with many unread messages. - Rate Limiting: Adjust API and other rate limits (
General
->Rate Limiter
) carefully based on your expected load and security needs. Too strict limits can impact usability; too loose can open doors for abuse. - Disable Unused Features/Apps: If you are not using certain features (e.g., Livechat, specific integrations), disabling them might save some resources.
- File Upload Limits: Setting excessively high file upload limits (
Tuning MongoDB
- RAM and Cache (
wiredTigerCacheSizeGB
): Ensure MongoDB has sufficient RAM and the WiredTiger cache is appropriately sized to hold the working set (most frequently accessed data and indexes). This is often the single most important factor for MongoDB performance. Monitor cache hit rates. - Indexes: Ensure necessary indexes exist and are used effectively. Add custom indexes cautiously if needed. Ensure indexes fit in RAM.
- Slow Query Analysis: Use the database profiler (
db.setProfilingLevel(1, { slowms: 100 })
) to log queries slower than a specified threshold (e.g., 100ms). Analyze the output (db.system.profile.find().pretty()
) to identify problematic queries and potentially add or modify indexes. Remember to disable the profiler after analysis (db.setProfilingLevel(0)
). - Hardware: Use fast SSDs (preferably NVMe SSDs) for MongoDB data files. Ensure sufficient CPU cores for concurrent operations.
- Read Scaling (Replica Set Secondaries): Configure your application (or MongoDB driver) to direct read operations to secondary nodes in your replica set (
readPreference=secondaryPreferred
orsecondary
). This can offload read workload from the primary but requires understanding potential data staleness (due to replication lag). Rocket.Chat's default settings might handle this, or specific read preferences could be set in the connection string options. Check Rocket.Chat and MongoDB driver documentation. - Sharding (Very Advanced): For extremely large deployments where a single replica set cannot handle the write load or data volume, MongoDB sharding can distribute data across multiple replica sets (shards). This adds significant operational complexity and is rarely needed unless dealing with massive scale (terabytes of data, very high throughput).
Tuning the Reverse Proxy (Nginx)
- Worker Processes/Connections: Tune Nginx
worker_processes
(often set toauto
or the number of CPU cores) andworker_connections
(maximum connections per worker) innginx.conf
based on your server resources and expected load. - Keepalive Connections: Enable keepalive connections (
keepalive_timeout
) between Nginx and clients, and potentially between Nginx and the upstream Rocket.Chat instances (keepalive
directive in theupstream
block) to reduce connection setup overhead. - Buffering: While we turned off
proxy_buffering
for the main/
location to improve real-time responsiveness, Nginx's buffering can be useful for serving static assets or handling slow clients. You might configure different buffering settings for different location blocks if needed. - Caching: Configure Nginx to cache static assets served by Rocket.Chat (though Rocket.Chat serves few static assets directly, mostly relies on client-side JS). More relevant if Nginx serves other content alongside Rocket.Chat.
proxy_cache_path
andproxy_cache
directives. - SSL/TLS Optimization: Use modern protocols (TLS 1.2, TLS 1.3), enable HTTP/2 (
http2
on thelisten
directive), configure strong cipher suites, and enable SSL session caching (ssl_session_cache
,ssl_session_timeout
) to speed up subsequent TLS handshakes. Certbot's defaultoptions-ssl-nginx.conf
usually provides good settings. - Gzip Compression: Enable Gzip compression (
gzip on;
) in Nginx to compress responses (like API responses, HTML, CSS, JS) sent to clients, saving bandwidth and improving load times. Ensure you configure appropriategzip_types
.
Monitoring Setup Example (Prometheus + Grafana)
A popular open-source monitoring stack:
- Install Prometheus: A time-series database and monitoring system.
- Install Exporters: Small applications that expose metrics in a format Prometheus can scrape:
node_exporter
: Exposes host system metrics (CPU, RAM, Disk, Network). Run on all monitored hosts.cadvisor
: Exposes container metrics. Run as a container.mongodb_exporter
: Connects to MongoDB and exposes its internal metrics. Run as a container or process.
- Configure Prometheus: Set up scrape jobs in
prometheus.yml
to periodically collect metrics from the exporters. - Install Grafana: A visualization platform.
- Configure Grafana: Add Prometheus as a data source. Import or create dashboards to visualize the collected metrics (e.g., dashboards for Node Exporter, Docker Containers, MongoDB). Dashboards for Rocket.Chat specific metrics might be available if using APM integration that exposes Prometheus metrics.
This setup allows you to track performance trends, correlate events, set up alerts (using Prometheus's Alertmanager), and gain deep visibility into your entire Rocket.Chat stack.
Workshop Identifying Potential Performance Issues
Objective
To use basic monitoring tools and Rocket.Chat's admin interface to identify potential areas for performance investigation. This workshop focuses on observation rather than implementing complex tuning.
Prerequisites
- A running Rocket.Chat instance (ideally with some simulated or real user activity).
- Access to the server terminal with
docker stats
,htop
(optional). - Access to
mongosh
(docker compose exec mongo mongosh
). - Administrator access to Rocket.Chat UI.
Steps
1. Observe Baseline Resource Usage * Check Container Stats:
Observe the typical CPU % and Memory Usage for both containers when the system is relatively idle. Note these baseline values. * (Optional) Check Host Stats: Observe overall system CPU and Memory usage. Note the baseline. Exithtop
.
2. Simulate Light Load (Manual)
* Open multiple browser tabs or use different user accounts (if available) to access your Rocket.Chat instance.
* Send some messages, switch between channels, open the Administration panel.
* While doing this, re-run docker stats rocketchat_mongo rocketchat_app
in the terminal.
* Observe: Do the CPU or Memory usage values spike significantly? Does one container consistently use more resources than the other under light load?
3. Check Application Logs for Errors/Warnings
* Go to Administration
-> Workspace
-> View Logs
in the Rocket.Chat UI.
* Scan the logs for any recent entries marked as ERROR
or WARN
.
* Observe: Are there recurring errors (e.g., database connection issues, permission errors, integration failures)? These can sometimes correlate with performance problems or indicate underlying issues.
4. Review Slow MongoDB Queries (Simulated) We'll use the profiler to see if any queries would be logged if they were slow. * Connect to MongoDB:
* Enable Profiling (Level 1 logs slow queries):use rocketchat
// Log operations slower than 200 milliseconds
db.setProfilingLevel(1, { slowms: 200 })
mongosh
terminal.
* Observe: If any queries took longer than 200ms, they will be listed here. Examine the op
(operation type), ns
(namespace/collection), command
or query
(details of the operation), millis
(duration), planSummary
(how MongoDB executed the query, including index usage).
* Note: On a fast, lightly loaded system, you might not see any queries logged even with a threshold like 200ms. You could lower slowms
temporarily (e.g., to 50) for testing, but remember higher levels of profiling impact performance.
* Disable Profiling: Important: Turn off the profiler when done.
5. Check Network Latency (Client-Side)
* Open your browser's Developer Tools (F12).
* Go to the "Network" tab.
* Reload your Rocket.Chat page (Ctrl+R or Cmd+R).
* Filter requests (e.g., by "XHR" or "Fetch" to see API calls, or look at WebSocket "WS" traffic).
* Observe: Are there specific API calls (/api/v1/...
) that take a long time (check the "Time" or "Latency" column)? Are assets (JS, CSS) loading quickly? High latency on API calls could indicate server-side processing delays, database slowness, or network issues between the client and server.
6. Review Instance Load (if using HA)
* (Conceptual, as we don't have HA) If you had multiple instances, you would check resource usage (docker stats
or system monitoring) on each instance.
* You would also check the load balancer stats to see how traffic is being distributed. Uneven distribution could indicate issues with the load balancing algorithm or sticky sessions.
Conclusion
This workshop provided hands-on steps for basic performance observation using readily available tools. You checked baseline resource usage, observed changes under simulated load, reviewed application logs for potential issues, used the MongoDB profiler to conceptualize slow query detection, and examined client-side network latency. While not deep tuning, these observational steps are crucial first actions when investigating performance complaints. They help narrow down whether the bottleneck is likely CPU, RAM, Disk, Network, Database, or Application code, guiding further investigation and tuning efforts using more advanced tools like APM or dedicated monitoring systems.
Troubleshooting Common Issues
Even with careful setup, you might encounter issues running a self-hosted Rocket.Chat instance. This section covers common problems and systematic approaches to diagnosing and resolving them.
Log Analysis (Rocket.Chat, Nginx, MongoDB)
Logs are your best friend when troubleshooting. Learn where to find them and what to look for.
- Rocket.Chat Logs:
- Location (Docker):
docker compose logs rocketchat
(ordocker compose logs -f rocketchat
to follow). - Location (UI):
Administration
->Workspace
->View Logs
. - What to look for:
ERROR
messages: Indicate serious problems (e.g., cannot connect to DB, critical function failure).WARN
messages: Indicate potential issues or non-critical failures.- Startup sequence: Check for errors during initialization (DB connection, migrations, setting up listeners).
- Specific feature errors: If uploads fail, look for logs related to file system access or S3 configuration. If emails fail, look for SMTP errors. If APIs fail, look for related stack traces.
- Set Log Level to Debug (0) temporarily for more verbose output during troubleshooting, but remember to set it back to Info (1) or Warn (2) afterwards.
- Location (Docker):
- Nginx Logs:
- Location (Defaults):
- Access Log:
/var/log/nginx/access.log
(or your custom path, e.g.,/var/log/nginx/rocketchat.access.log
). Records all incoming requests processed by Nginx. - Error Log:
/var/log/nginx/error.log
(or your custom path, e.g.,/var/log/nginx/rocketchat.error.log
). Records errors encountered by Nginx (e.g., cannot connect to upstream, SSL handshake failures, configuration errors).
- Access Log:
- What to look for:
- Error Log: Search for
[error]
,[crit]
,[emerg]
tags. Look for messages likeconnect() failed
,upstream timed out
,no live upstreams
, SSL certificate errors, permission denied errors. - Access Log: Check HTTP status codes for requests to your Rocket.Chat domain.
502 Bad Gateway
: Nginx cannot reach the upstream Rocket.Chat application (Rocket.Chat container might be down, crashed, or unresponsive, or network issue between Nginx and container). Check Rocket.Chat logs.504 Gateway Timeout
: Nginx connected to Rocket.Chat, but Rocket.Chat took too long to respond. Indicates slowness in Rocket.Chat or the database. Check Rocket.Chat and MongoDB performance.4xx
errors: Client errors (e.g.,400 Bad Request
,401 Unauthorized
,403 Forbidden
,404 Not Found
). Might indicate issues with API calls, permissions, or incorrect URLs.500 Internal Server Error
: Usually indicates an error within Nginx itself or sometimes propagated from the upstream. Check Nginx error log.
- Error Log: Search for
- Location (Defaults):
- MongoDB Logs:
- Location (Docker):
docker compose logs mongo
. - Location (Default Host Install): Typically
/var/log/mongodb/mongod.log
. - What to look for:
- Connection errors (e.g., authentication failures).
- Slow query warnings (if enabled).
- Replication errors or status changes (primary elections, secondary falling behind).
- Storage engine errors (WiredTiger issues).
- Disk space warnings.
- Startup/shutdown messages and errors.
- Network errors (e.g.,
SocketException
).
- Location (Docker):
Systematic Approach:
- Identify the Symptom: What exactly is failing? (e.g., Cannot log in, messages not sending, page not loading, file upload error).
- Check Nginx Logs: Start with the entry point. Are requests reaching Nginx? Is Nginx reporting errors connecting to the upstream?
- Check Rocket.Chat Logs: Look for errors corresponding to the time the issue occurred. Are there database errors, application exceptions, or specific feature failures logged?
- Check MongoDB Logs: If Rocket.Chat logs indicate database issues, check MongoDB logs for connection problems, slow queries, or replication issues.
- Check System Resources: Are CPU, RAM, or Disk usage maxed out (
htop
,docker stats
)? - Reproduce the Issue: Can you reliably reproduce the problem? What are the exact steps?
- Isolate the Change: Did the issue start after a specific change (e.g., Rocket.Chat update, configuration change, system update)?
Connectivity Issues (Firewall, DNS, Reverse Proxy)
Problems accessing Rocket.Chat often stem from networking or configuration issues.
- Firewall:
- Symptom: Cannot connect to
https://chat.example.com
at all (browser times out or connection refused). - Check: Ensure your host firewall (
ufw status verbose
) allows incoming traffic on ports 80 and 443. Check cloud provider security groups/firewalls as well. Ensure Nginx is running (sudo systemctl status nginx
).
- Symptom: Cannot connect to
- DNS:
- Symptom: Browser shows "Server not found" or "DNS address could not be found" for
chat.example.com
. - Check:
- Use
ping chat.example.com
andnslookup chat.example.com
(ordig chat.example.com
) from both your client machine and the server itself. Do they resolve to the correct public IP address of your server? - Check your domain's DNS records (A record) with your DNS provider. Ensure it points to the correct IP. Allow time for DNS propagation if you recently changed records.
- Use
- Symptom: Browser shows "Server not found" or "DNS address could not be found" for
- Reverse Proxy (Nginx):
- Symptom: Getting default Nginx page, "502 Bad Gateway", "504 Gateway Timeout", SSL certificate errors, WebSocket connection failures (real-time features broken).
- Check:
- Configuration Syntax:
sudo nginx -t
. Fix any reported errors. - Configuration Logic: Review
/etc/nginx/sites-available/rocketchat
.- Is
server_name
correct? - Is the
upstream
block correct and pointing to the right internal IP/port (127.0.0.1:3000
)? - Are SSL certificate paths correct (
ssl_certificate
,ssl_certificate_key
) and files readable by Nginx? Usesudo certbot certificates
to check certificate status and paths. - Are WebSocket headers (
Upgrade
,Connection
) configured correctly in thelocation /
block? - Is Nginx reloaded after changes (
sudo systemctl reload nginx
)?
- Is
- Upstream Status: Is the Rocket.Chat container running (
docker compose ps
)? Check Rocket.Chat logs if Nginx reports 502 errors. - SSL Errors: Check certificate validity (
openssl s_client -connect chat.example.com:443
). Ensure Certbot renewal is working (sudo certbot renew --dry-run
).
- Configuration Syntax:
- Rocket.Chat
ROOT_URL
:- Symptom: Pages load partially, assets (CSS/JS) missing (404 errors in browser console), OAuth redirects fail, invitation links incorrect.
- Check: Ensure the
ROOT_URL
environment variable in yourdocker-compose.yml
exactly matches the URL users access, including the protocol (https://
) and domain name. Restart Rocket.Chat (docker compose down && docker compose up -d
) after changing it.
Update and Migration Problems
Updates can sometimes introduce issues if not performed carefully.
- Backup First: ALWAYS back up your database (MongoDB dump) and volumes (Docker volumes for uploads, if using filesystem) before performing any major update (Rocket.Chat, MongoDB, Node.js).
- Read Release Notes: Carefully read the release notes for the Rocket.Chat version you are upgrading to. Pay attention to:
- Breaking changes.
- Required MongoDB version compatibility.
- Required Node.js version compatibility (less critical with Docker, as the image includes the correct Node version).
- Specific upgrade instructions or potential issues.
- Docker Image Updates:
- Change the image tag in
docker-compose.yml
(e.g., fromrocketchat/rocket.chat:6.5.2
torocketchat/rocket.chat:6.6.0
). Pinning versions is safer than usinglatest
. docker compose pull rocketchat
(ordocker pull rocketchat/rocket.chat:6.6.0
)docker compose down
(stop existing containers)docker compose up -d
(start with the new image)
- Change the image tag in
- Migration Scripts: Rocket.Chat often runs database migration scripts on startup after an update.
- Symptom: Slow startup after update, high CPU usage, errors in logs related to "Migrations".
- Action: Be patient, especially with large databases. Monitor logs. If migrations fail repeatedly, check logs for specific errors, consult Rocket.Chat documentation/forums, and potentially restore from backup if the database gets into an inconsistent state.
- MongoDB Version Compatibility: Ensure the MongoDB version you are running is supported by the Rocket.Chat version you are upgrading to. Check Rocket.Chat documentation for compatibility matrix. Upgrading MongoDB itself requires careful planning (usually upgrade one version at a time, follow MongoDB upgrade guides).
- Configuration Changes: New versions might introduce new settings or deprecate old ones. Review settings after an upgrade. Custom CSS or JavaScript might break if internal class names or structures change.
Specific Feature Failures (e.g., File Uploads, Notifications)
- File Uploads Failing:
- Check Permissions: If using
FileSystem
storage, ensure the directory on the host (mapped to/app/uploads
) has correct permissions for the user ID running inside the Rocket.Chat container (often1000
ornode
).sudo chown -R <user_id>:<group_id> /path/to/host/uploads
. - Check Disk Space: Is the volume full (
df -h
)? - Check Nginx
client_max_body_size
: Ensure Nginx limit is >= Rocket.Chat's upload limit setting. Check Nginx error logs for related errors. - Check Rocket.Chat Logs: Look for errors related to storage type (FileSystem, S3, MinIO), permissions, or connection issues (if using S3/MinIO).
- Check S3/MinIO Config: If using object storage, double-check bucket names, region, credentials, and CORS policies on the bucket.
- Check Rocket.Chat Upload Settings:
Administration
->Settings
->File Upload
. VerifyStorage Type
, limits, accepted media types.
- Check Permissions: If using
- Push Notifications Not Working (Mobile):
- Check Registration: Is your server registered with Rocket.Chat Cloud (
Administration
->Workspace
->Registration
)? Registration is usually required for the default push gateway. - Check Gateway: Ensure
Administration
->Settings
->Push
->Enable Gateway
isTrue
. - Check Logs: Look for errors related to push notifications.
- Firewall: Ensure your server can make outgoing connections to Rocket.Chat's push servers (check Rocket.Chat docs for specific endpoints/IPs if behind a restrictive egress firewall).
- Self-Hosted Gateway (Advanced): If running your own push gateway, ensure it's configured correctly and reachable.
- Check Registration: Is your server registered with Rocket.Chat Cloud (
- Email Notifications/SMTP Failing:
- Check SMTP Config:
Administration
->Settings
->Email
->SMTP
. Verify Host, Port, Username, Password, From Email, TLS settings. - Use "Send Test Email" button: Does it succeed?
- Check Rocket.Chat Logs: Look for detailed SMTP error messages.
- Check SMTP Provider: Are credentials correct? Is the account active? Are there sending limits? Check provider's dashboard/logs. Check SPF/DKIM/DMARC records for deliverability.
- Firewall: Ensure outgoing connections are allowed on the SMTP port.
- Check SMTP Config:
- Video/Audio Calls Failing:
- WebRTC (Built-in): Requires specific ports to be open (UDP range, TURN/STUN server configuration). Check
Administration
->Settings
->WebRTC
. Ensure TURN/STUN servers are configured correctly and reachable. Firewall configuration for UDP is often complex. - Jitsi Integration: Ensure
Administration
->Settings
->Video Conference
points to the correct Jitsi domain and SSL settings are right. Test accessing your Jitsi domain directly. Check Nginx/Jitsi logs if self-hosting Jitsi.
- WebRTC (Built-in): Requires specific ports to be open (UDP range, TURN/STUN server configuration). Check
General Troubleshooting Mindset:
* Be Systematic: Don't change multiple things at once.
* Check the Obvious: DNS, firewalls, service status (systemctl status nginx
, docker compose ps
).
* Read the Logs: They contain the most detailed clues.
* Consult Documentation: Rocket.Chat docs, Nginx docs, MongoDB docs.
* Search Online: Use specific error messages from logs to search forums, GitHub issues, Stack Overflow.
* Test in Isolation: Can Nginx reach the Rocket.Chat container? Can Rocket.Chat reach the MongoDB database? Can the server reach external services (SMTP, Jitsi)?
* Ask for Help: If stuck, provide detailed information (versions, configuration, logs, steps to reproduce) on forums or community channels.
Workshop Troubleshooting a Common Problem (502 Bad Gateway)
Objective
To simulate and troubleshoot a common "502 Bad Gateway" error, which occurs when the Nginx reverse proxy cannot communicate with the backend Rocket.Chat application container.
Prerequisites
- A running Rocket.Chat instance behind an Nginx reverse proxy (as set up previously).
- Access to the server terminal.
- Access to Rocket.Chat UI and Nginx logs.
Steps
1. Simulate the Problem: Stop the Rocket.Chat Container
The most direct way to cause a 502 error is to stop the backend application that Nginx is trying to proxy to.
cd ~/rocketchat-server
docker compose stop rocketchat # Stop only the rocketchat service, leave mongo running
2. Observe the Symptom
- Open your web browser and try to access your Rocket.Chat instance via its HTTPS domain (e.g.,
https://chat.example.com
). - Expected Result: You should see an Nginx error page displaying "502 Bad Gateway".
3. Start Troubleshooting: Check Nginx
-
Check Nginx Status: First, ensure Nginx itself is running.
It should beactive (running)
. If not, start it (sudo systemctl start nginx
) and check its config (sudo nginx -t
). -
Check Nginx Error Logs: This is the key step for diagnosing proxy errors.
(Replacerocketchat.error.log
if you used a different custom log file name).- Look for recent errors (around the time you tried accessing the site): You should see entries similar to this: Or potentially:
- Interpretation: The
connect() failed (111: Connection refused)
orno live upstreams
message clearly indicates that Nginx tried to connect to the upstream defined in yourupstream rocketchat_servers
block (specificallyhttp://127.0.0.1:3000
in our single-instance setup) but failed. This points the finger directly at the backend application.
4. Check the Backend Application (Rocket.Chat Container)
- Check Container Status: Use
docker compose ps
to see the state of your containers.- Expected Result: You will see that the
rocketchat_app
container has anExit
status or is listed asstopped
. Therocketchat_mongo
container should still beUp
. - Conclusion: The backend Rocket.Chat application is not running, which is why Nginx couldn't connect to it, resulting in the 502 error.
- Expected Result: You will see that the
5. Resolve the Issue: Start the Rocket.Chat Container
-
Start the stopped container:
Or, if you had useddocker compose down
, you would usedocker compose up -d
. -
Verify Container is Running: Check
docker compose ps
again. Therocketchat_app
container should now show a status ofUp
. -
Check Rocket.Chat Logs (Optional but good practice): Ensure it started without errors.
Look for theSERVER RUNNING
message. PressCtrl+C
to exit logs.
6. Verify the Fix
- Go back to your web browser and refresh the Rocket.Chat page (
https://chat.example.com
). - Expected Result: The 502 error should be gone, and your Rocket.Chat login page or workspace should load correctly.
7. (Self-Study) Other Potential Causes for 502
While we simulated a stopped container, other issues could cause a 502:
- Rocket.Chat Crashed: The container might be running (
docker compose ps
showsUp
), but the Node.js process inside crashed. Checkingdocker compose logs rocketchat
would reveal crash errors. Restarting the container (docker compose restart rocketchat
) might fix it temporarily, but investigating the crash reason is needed. - Incorrect Upstream Address: Nginx configuration points to the wrong IP or port for the Rocket.Chat container.
- Firewall Blocking Internal Connection: A host firewall rule accidentally blocks connections from Nginx (usually running as user
www-data
) to port 3000 on127.0.0.1
(less common, but possible with complex firewall setups). - Resource Exhaustion: The Rocket.Chat container might be unresponsive because the server is out of RAM or CPU resources. Check
htop
ordocker stats
.
Conclusion
In this workshop, you successfully diagnosed and resolved a common "502 Bad Gateway" error. By checking the Nginx error log, you identified that the issue was with the upstream connection. You then confirmed the backend Rocket.Chat container was stopped using docker compose ps
. Starting the container resolved the problem. This demonstrates a logical troubleshooting workflow: start at the entry point (Nginx), check its logs for upstream errors, then investigate the status and logs of the upstream application (Rocket.Chat).