How to Deploy Web Apps Using Kamal in 2024: Effective Containerized Application Deployment

How to Deploy Web Apps Using Kamal in 2024: Effective Containerized Application Deployment

Deploying a containerized web application can often seem daunting. Kamal is a tool designed to streamline and simplify the deployment of web apps, making your workflow more efficient and reliable.

In this article, you’ll learn how to deploy web apps using Kamal on a virtual private server (VPS) environment. We’ll also provide several best practices to enhance your application deployment process.

By the end of this guide, you’ll be well-equipped to leverage the power of Kamal for your projects. Let’s get started.

Download Free Docker Cheat Sheet

Kamal is a deployment tool that facilitates the efficient rollout of web apps. It integrates essential services and operations into a cohesive workflow, making web app deployment with Kamal streamlined and less error-prone.

Designed to manage and automate the deployment of web applications, Kamal reduces the complexity often associated with manual server and service management. It allows developers to focus on building and updating their web apps without the overhead of deployment logistics.

Kamal supports deployments ranging from a bare metal server to a single VM. It offers zero-downtime deployments, rolling restarts, asset bridging, remote builds, and comprehensive accessory service management.

With Kamal, you can effortlessly deploy web apps, configure servers, manage databases, and handle traffic balancing. This tool supports various environments, making it versatile for deploying web applications across different platforms.

Why Use Kamal for Web App Deployment?

Kamal official homepage

Choosing Kamal for your web app deployment offers several benefits for developers and businesses. Here’s what makes Kamal stand out:

  • Simplicity – Kamal’s straightforward approach to deployment cuts through the often steep learning curve associated with other deployment tools. It simplifies the process, enabling application deployment with just a few Linux commands.
  • Automation – Kamal automation for deployments streamlines your workflows. From updates to scaling, Kamal automates these tasks, ensuring they are completed quickly and consistently. This means less time on manual processes and more on development.
  • Reliability – with Kamal, you can expect stable releases. Its structured deployment process minimizes the errors that can occur with manual deployments, ensuring your web application runs smoothly and reliably.
  • Suitability – Kamal is exceptionally compatible with Linux VPS environments. Its alignment with Linux servers means you can harness the full potential and flexibility of deploying applications on Linux VPS hosting.

How to Deploy Web Apps Using Kamal

In this section, you’ll learn how to use Kamal to streamline your web app deployment process.

1. Prepare for Deployment

Whether using a local machine or a virtual server, preparing the prerequisites ensures a smooth web application deployment with Kamal. In this example, we’ll use Hostinger’s VPS hosting to set up your environment for deploying a web app.

Hostinger’s VPS offers a reliable server that sets the stage for your deployment needs. It provides top-notch security measures, easy scalability to grow alongside your application, and an AI assistant to simplify your development and deployment processes.

After preparing your VPS, access your server with PuTTY or any other SSH client. Then, update your Linux packages with the following SSH commands:

sudo apt-get update && sudo apt-get upgrade

Next, set up the software environment required by your web app, which may include installing a web server like Apache or NGINX and setting up a database such as MySQL or PostgreSQL. It’s also critical to secure your server with firewalls and SSH keys for safe access.

If you are developing a Rails app, ensure you have installed the Ruby on Rails framework. Otherwise, you can install Docker and manage containers for your application.

2. Install and Deploy with Kamal

Once your environment is ready, proceed with the Kamal installation. For those with a Ruby environment, install Kamal globally on your Linux VPS with the following command:

gem install kamal

This makes Kamal accessible from any directory within your server.

If you prefer containerization in Kamal deployments, pull the Docker image and set an alias in your shell config file. This allows you to use Kamal commands without installing the dependencies on your server.

Next, navigate to the config directory and open the deploy.yml file. Here, you can specify details such as deployment stages, public IP addresses, and the repository URL for version control with Kamal.

Your deploy.yml file will also include registry details. If you’re using Docker Hub, you won’t need to specify a server because it’s the default.

Here’s a basic example of what the deploy.yml content might include:

# Your web app name. Used to uniquely configure containers.
service: hey
# Your image host or container image name
image: 37s/hey
servers:
  - 192.168.0.1
  - 192.168.0.2
registry:
  # The container registry server, if you're not using Docker Hub
  # server: ghcr.io / ...
  username: registry-user-name
  password:
    secure: KAMAL_REGISTRY_PASSWORD
env:
  secret:
    secure: RAILS_MASTER_KEY
#Configure a custom healthcheck
healthcheck:
  path: /healthz
  port: 4000
  max_attempts: 7
  interval: 20s

Remember to keep your credentials secure by replacing KAMAL_REGISTRY_PASSWORD with your Docker registry access token.

With your config file set up, it’s time to start the deployment process. For initial deployment, run:

kamal setup

This prepares your servers by creating directories, setting permissions, and performing other required tasks.

For subsequent deployments, use:

kamal deploy

This command executes the tasks outlined in your deploy.yml file, such as code updates, migrations, and service restarts.

3. Push Environment Files

To effectively deploy your web app using Kamal, it’s vital to manage your environment files meticulously. These files contain environment variables critical for configuring your application across various development, testing, and production settings.

For security reasons, your application’s ENV files should never be included in version control. Instead, leverage Kamal’s robust environment management features to transfer these files to your server securely.

Start by securing your environment file in a safe storage location. Consider using Hostinger’s VPS to reliably manage your application’s environment variables, ensuring they are securely applied and maintained consistently throughout deployment.

Next, utilize the kamal env push command to transfer the file to your server securely.

Whenever you add new or modify existing environment variables in your ENV file, remember to push these updates to your remote servers using kamal env push. Before executing the kamal deploy command, complete this step to ensure that your deployment process incorporates the updated variables into your app’s container.

These procedures are critical for adequately operating Docker containers and services, as they rely on the correct configuration settings provided by the environment variables.

4. Run Commands on Servers

To simplify your web application management, Kamal provides a user-friendly feature that allows you to execute commands across your server infrastructure efficiently.

For instance, to run a command on all your servers to check the Ruby version, you would use:

kamal app exec 'ruby -v'

The output will confirm the Ruby version on each app host, for example:

App Host: 192.168.0.1
ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [x86_64-linux]
App Host: 192.168.0.2
ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [x86_64-linux]

To target only the primary server, the command would be:

kamal app exec --primary 'cat .ruby-version'

If you need to run a Rails-related command across all servers, such as checking the Rails environment setup, you will input the following:

kamal app exec 'bin/rails about'

The output should look like this:

App Host: 192.168.0.1
About your application's environment
Rails version:             7.1.0.alpha
Ruby version:              ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [x86_64-linux]
RubyGems version:          3.3.26
Rack version:              2.2.5
Middleware:                ActionDispatch::HostAuthorization, Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, ActionDispatch::RemoteIp, Rails::Rack::Logger, ActionDispatch::ShowExceptions, Action Dispatch::DebugExceptions, Action Dispatch::Callbacks, Action Dispatch::Cookies, Action Dispatch::Session::CookieStore, Action Dispatch::Flash, Action Dispatch::ContentSecurityPolicy::Middleware, Action Dispatch::PermissionsPolicy::Middleware, Rack::Head, Rack::ConditionalGet, Rack::ETag, Rack::TempfileReaper
Application root:          /rails
Environment:               production
Database adapter:          sqlite3
Database schema version:   20221231233303

For more interactive tasks like launching a Rails console or a bash session, Kamal simplifies the process. Just execute the following commands to start a bash session in either a new app image container or the currently running Docker container:

# New container bash session
kamal app exec -i bash
# Reuse the current container for bash session
kamal app exec -i --reuse bash
# New container Rails console
kamal app exec -i 'bin/rails console'

5. Check Server State with Kamal Details

Understanding the state of your servers is crucial for maintaining their health and ensuring that your applications run smoothly. Kamal provides an efficient way to monitor this through the details command.

Executing kamal details gives you a snapshot of your containers, their status, and how they are performing. Here’s what you’ll typically see:

For Traefik containers:

Traefik Host: 192.168.0.1
CONTAINER ID   IMAGE    COMMAND                 CREATED          STATUS          PORTS
6195b2a28c81   traefik  "/entrypoint.sh…" 30 minutes ago   Up 19 minutes   0.0.0.0:80->80/tcp...

For your application containers:

App Host: 192.168.0.1
CONTAINER ID   IMAGE                     COMMAND          CREATED         STATUS          PORTS
badb1aa51db3   registry.domain.tld/...  "/rails/bin/…"  13 minutes ago  Up 13 minutes   3000/tcp

This output lets you quickly verify that containers are up and running and that the ports are correctly mapped, indicating a healthy server state.

For a more focused inspection, you can narrow the details to app-specific or Traefik-specific containers using kamal app details or kamal traefik details, respectively.

These targeted commands provide direct access to logs and container specifics, streamlining the process of managing environment configurations and simplifying error handling in Kamal deployments.

6. Rollback Deployments

When a deployment doesn’t go as planned, Kamal provides a simple rollback process. It involves reactivating a previously stable Docker container. To manage a quick and efficient rollback, follow these steps:

First, identify the old containers available using the kamal app containers command. This will list both active and inactive containers. Look for the last active container by its image tag or ID before the failed deployment.

For example, you might see an output showing:

App Host: 192.168.0.1
CONTAINER ID   IMAGE               COMMAND                  STATUS
1d3c91ed1f51   [previous_image]    "/rails/bin/docker-e…"   Up 19 minutes
539f26b28369   [failed_image]      "/rails/bin/docker-e…"   Exited (1) 27 minutes ago

To rollback, execute kamal rollback [previous_image_tag]. Kamal will stop the current problematic container and restart the last stable one. With the previous container already on the host, the rollback happens rapidly without pulling from the registry again.

Note that old containers are automatically purged after three days following a new kamal deploy, so it’s advisable to confirm the success of your deployment within this timeframe to retain the option for a swift rollback.

It’s also essential to ensure you have the proper backup and recovery with Kamal to safeguard against unforeseen issues. Hostinger’s VPS hosting includes automated backups, seamlessly enhancing your rollback capabilities.

7. Clean Up Servers with Kamal Remove

Managing server space and performance involves removing unused applications. With Kamal, cleaning up your server is straightforward. When deleting an entire application, execute the kamal remove command.

Kamal will then remove all components associated with the application on the server, including stopping and removing Docker containers, erasing any Docker image, and clearing any associated registry sessions.

This command is handy to ensure your server remains uncluttered and performs optimally. However, it’s essential to use this feature with caution. Before running kamal remove, ensure you have backups of any data you wish to keep.

8. Reboot Traefik

When managing a load balancer and reverse proxy, especially on an NGINX server, there may be occasions when you need to reboot Traefik, the service that routes your HTTP traffic. This need typically arises after updates to Traefik’s arguments or labels, necessitating a reboot for changes to take effect.

To reboot Traefik using Kamal, utilize the following command:

kamal traefik reboot

This will restart the Traefik service, implementing your new configurations. However, in a production environment, where stability and uptime are critical, opt for the rolling reboot feature:

kamal traefik reboot --rolling

A rolling reboot methodically restarts Traefik containers sequentially, ensuring no downtime and maintaining continuous load-balancing functionality. This safer approach ensures that your web applications remain accessible to users while updates proceed in the background.

Best Practices for Deploying Web Applications with Kamal

After learning how to deploy your web application to a server, let’s explore some Kamal deployment best practices for smooth and efficient web app management.

Automate Your Deployment Workflow

Embracing Kamal automation for deployments transforms repetitive manual tasks into a one-click operation. Kamal’s commands and scripts allow you to automate your web applications’ initial setup, updates, and ongoing maintenance, making the deployment process quicker and more reliable by reducing human error.

Integrating Kamal deployment automation tools within CI/CD pipelines further enhances efficiency. These pipelines promote continuous improvement and seamless updates, enabling an uninterrupted flow from development to deployment.

Hostinger’s VPS hosting is ideally suited to these practices, offering an AI Assistant to streamline script automation for managing and scaling your web applications effortlessly. You can consult the Hostinger VPS AI assistant for instructions on automating your deployment workflow.

For example, initiate a VPS AI prompt like “How do I automate database server backups using Kamal?”

Our AI assistant will then provide a comprehensive step-by-step guide. You can ask follow-up questions to expand on each step if you need further details. The Hostinger VPS AI assistant can also supply application code templates to speed up the setup process.

Deploy Lock and Safe Concurrent Operations

Managing concurrent operations is essential when deploying web applications to prevent conflicts and preserve the integrity of your applications. Kamal facilitates this with a deploy lock feature, a coordination mechanism that allows only one deployment at a time.

Here’s how to incorporate a deploy lock into your Kamal deployment strategies:

Before Deployment

Initiate a deploy lock to preclude overlapping deployment processes using the command kamal lock acquire -m “Your reason for locking”. This creates a kamal_lock directory on the primary server, indicating that a deployment process is underway.

During Deployment

Verify the lock status with kamal lock status to determine who has initiated the lock and for what purpose, as well as which version is being deployed. You might see an output similar to this:

Locked by: A.N. Other on 2023-03-24 09:49:03 UTC
Version: 77f45c0686811c68989d6576748475a60bf53fc2
Message: Automatic deploy lock

This output helps you stay informed about ongoing deployment activities and ensures no conflicting operations are conducted.

After Successful Deployment

Conclude your deployment by releasing the deploy lock with kamal lock release. This action is crucial for clearing the environment for future implementations and ensuring continuous deployment operations.

Use Kamal Hooks

Kamal provides a hook system that allows developers to execute custom scripts at predefined points in the deployment process, offering tailored automation and ensuring the deployment’s integrity and reliability. They come in four types:

  • Pre-connect hooks – executed before Kamal takes a deploy lock and before connecting to the remote hosts. These hooks are useful for DNS warming tasks.
  • Pre-build hooks – run before the build process starts, allowing for pre-build validations like checking for uncommitted changes or ensuring continuous integration (CI) has passed.
  • Pre-deploy hooks – triggered right before the deployment starts, suitable for final checks like verifying CI completion.
  • Post-deploy hooks – activated after a deploy, redeploy, or rollback hook. Post-deploy hooks can send deployment notifications or register the new version with an application performance management (APM) system.

The scripts in these hooks have access to a range of KAMAL_* environment variables, which provide detailed context about the deployment, including timestamps, user information, version details, and host lists. If any script exits with a non-zero status, the deployment process will be aborted to prevent potential errors from propagating.

Here is one example of creating a post-deploy hook script that sends a deployment notification to a chatbot in Basecamp using the KAMAL_* variables:

#!/usr/bin/env bash
curl -q -d "content=[My App] ${KAMAL_PERFORMER} Rolled back to version ${KAMAL_VERSION}" https://3.basecamp.com/XXXXX/integrations/XXXXX/buckets/XXXXX/chats/XXXXX/lines

This script would post a message indicating who performed the rollback and to which version.

In situations where hooks are not needed, you can bypass them by using the –skip_hooks flag during deployment commands, which prevents the execution of these custom scripts.

Conclusion

Throughout this guide, you’ve discovered what Kamal is, its advantages, and the steps for deploying web apps using Kamal on a Linux VPS. You’ve also learned Kamal deployment tips, such as workflow automation, securing operations with deploy locks, and optimizing processes with Kamal hooks.

As you continue to seek improvements for your web applications, consider using Hostinger’s VPS hosting. Our plans begin at just RM25.99/month, each packed with a suite of features to elevate your success.

These include complimentary real-time snapshots, automatic weekly backups, and access to an AI Assistant, each designed to complement your deployment strategy and boost your project’s performance.

Embrace the strength of Hostinger’s VPS hosting for your Kamal-powered web app deployments. Unleash the full potential of your online presence by clicking the banner below!

Deploy Web Apps Using Kamal FAQ

This section will answer the most common questions about how to deploy web apps using Kamal.

What Are the Prerequisites for Using Kamal to Deploy Web Apps?

Before deploying with Kamal, ensure your machine has Git installed for version control, SSH access to your server for secure connections, and a Rails app environment with the necessary dependencies resolved. These prerequisites are crucial for a seamless Kamal deployment process.

Can I Deploy Different Types of Web Applications With Kamal?

Yes, Kamal can handle different types of web applications beyond just Rails apps. It provides a flexible deployment system suitable for various web application frameworks, ensuring developers can deploy their projects effectively regardless of the underlying technology.

Is Kamal Suitable for Scaling Web Applications?

Kamal is ideal for scaling web apps as it supports deployment across multiple hosts and integrates with a load balancer, essential for traffic distribution and ensuring high availability as your user base and traffic expand.

Author
The author

Ariffud Muhammad

Ariffud is a Technical Content Writer with an educational background in Informatics. He has extensive expertise in Linux and VPS, authoring over 200 articles on server management and web development. Follow him on LinkedIn.