How to Deploy to Heroku
How to Deploy to Heroku Deploying web applications to the cloud has become a fundamental skill for developers, regardless of experience level. Among the many cloud platforms available, Heroku stands out as one of the most accessible and developer-friendly options for deploying applications quickly and reliably. Originally launched in 2007, Heroku abstracts away much of the complexity associated wi
How to Deploy to Heroku
Deploying web applications to the cloud has become a fundamental skill for developers, regardless of experience level. Among the many cloud platforms available, Heroku stands out as one of the most accessible and developer-friendly options for deploying applications quickly and reliably. Originally launched in 2007, Heroku abstracts away much of the complexity associated with server configuration, networking, and scalingallowing developers to focus on writing code rather than managing infrastructure.
Whether youre building a personal portfolio site, a startup MVP, or a small-scale SaaS product, deploying to Heroku offers a streamlined path from local development to a live, publicly accessible application. This tutorial provides a comprehensive, step-by-step guide to deploying applications to Heroku, covering everything from account setup to advanced configuration. By the end of this guide, youll not only know how to deploy your first app to Herokuyoull also understand best practices, common pitfalls, and how to optimize your deployments for performance, security, and scalability.
Heroku supports multiple programming languagesincluding Node.js, Python, Ruby, Java, PHP, Go, and Scalamaking it an ideal choice for teams working across diverse tech stacks. Its integration with Git, automatic build processes, and one-click add-ons for databases, monitoring, and logging make it an excellent platform for both beginners and experienced engineers.
In this guide, well walk through the entire deployment lifecycle, explore industry-standard best practices, recommend essential tools, examine real-world deployment examples, and answer the most common questions developers face when deploying to Heroku. Lets begin.
Step-by-Step Guide
1. Create a Heroku Account
Before you can deploy anything, you need a Heroku account. Visit https://signup.heroku.com and sign up using your email address, or authenticate via Google or GitHub. Heroku offers a free tier that is sufficient for learning, testing, and deploying small applications with limited traffic.
Upon signing up, youll be directed to the Heroku Dashboarda centralized interface where you can manage your apps, view logs, configure settings, and install add-ons. Familiarize yourself with the dashboard layout; youll return to it frequently during the deployment process.
2. Install the Heroku CLI
The Heroku Command Line Interface (CLI) is the primary tool for deploying and managing applications from your terminal. It allows you to create apps, push code, view logs, manage environment variables, and scale dynosall without leaving your terminal.
To install the Heroku CLI:
- macOS: Use Homebrew:
brew tap heroku/brew && brew install heroku - Windows: Download the installer from Heroku CLI Download Page
- Linux: Use curl:
curl https://cli-assets.heroku.com/install.sh | sh
After installation, verify it works by running:
heroku --version
You should see a version number (e.g., heroku/7.60.0). If not, restart your terminal or check your PATH environment variables.
3. Log in to Heroku via CLI
Once the CLI is installed, authenticate it with your Heroku account:
heroku login
This command opens a browser window where youll be prompted to log in. After successful authentication, the CLI will store your credentials locally. Alternatively, you can use the API key method for headless environments:
heroku auth:login
or
heroku auth:whoami
to confirm your login status.
4. Prepare Your Application
Heroku expects applications to follow specific conventions depending on the language/framework used. The key requirement is that your app must be able to start via a command defined in a Procfile. This file tells Heroku how to launch your application.
For example, if youre deploying a Node.js app:
web: node index.js
For a Python Flask app:
web: gunicorn app:app
For a Ruby on Rails app:
web: bundle exec puma -C config/puma.rb
Place the Procfile in the root directory of your project. It must be named exactly Procfile (no extension). If you're using a framework like Express.js, Django, or Laravel, ensure your app listens on the port specified by the PORT environment variable, which Heroku dynamically assigns.
In Node.js:
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(Server running on port ${port});
});
In Python (Flask):
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)))
Also ensure your project includes all necessary dependency files:
- Node.js:
package.jsonand optionallypackage-lock.json - Python:
requirements.txt - Ruby:
Gemfile - Java:
pom.xmlorbuild.gradle
Heroku automatically detects your apps language based on these files and uses the appropriate buildpack to compile and prepare your app for runtime.
5. Initialize a Git Repository
Heroku deploys applications via Git. If your project isnt already under version control, initialize a Git repository in your project directory:
git init
git add .
git commit -m "Initial commit"
Heroku uses Git as its deployment mechanism, so even if youre not collaborating with others, having a Git repository is mandatory.
6. Create a Heroku App
From your projects root directory, run:
heroku create
This command creates a new app on Heroku with a random name (e.g., thawing-basin-12345). Heroku also automatically adds a remote called heroku to your Git repository.
To specify a custom name, use:
heroku create your-app-name
Ensure the name is unique across all Heroku apps. If the name is taken, Heroku will prompt you to choose another.
You can verify the remote was added by running:
git remote -v
You should see output similar to:
heroku https://git.heroku.com/your-app-name.git (fetch)
heroku https://git.heroku.com/your-app-name.git (push)
7. Deploy Your Code
Deploying your app is as simple as pushing to the Heroku remote:
git push heroku main
If your default branch is named master instead of main, use:
git push heroku master
Heroku will detect your apps language, install dependencies, compile assets (if applicable), and start your app using the command in your Procfile. Youll see real-time logs in your terminal during the build process.
Once the build completes successfully, Heroku will display a URL where your app is live:
https://your-app-name.herokuapp.com
Open that URL in your browser to see your deployed application.
8. View Logs and Debug Issues
If your app fails to start or throws an error, use the logs to diagnose the issue:
heroku logs --tail
This command streams live logs from your app. Common errors include:
- Missing Procfile
- Incorrect start command
- Port not bound to
process.env.PORT - Missing dependencies in package.json or requirements.txt
- Environment variables not set
For a one-time view of logs, omit the --tail flag:
heroku logs
9. Configure Environment Variables
Many applications rely on secrets or configuration values that shouldnt be stored in codelike API keys, database URLs, or JWT secrets. Heroku allows you to set environment variables via the CLI:
heroku config:set API_KEY=your-secret-key
To view all environment variables:
heroku config
To remove a variable:
heroku config:unset API_KEY
For applications using a .env file during local development, use the heroku-config plugin to sync variables:
heroku plugins:install heroku-config
heroku config:push
This exports your local .env variables to Heroku automatically.
10. Scale Your App
By default, Heroku runs your app on a single free dyno (a lightweight container). To handle more traffic or improve performance, you can scale up:
heroku ps:scale web=2
This runs two web dynos. You can also scale to higher-tier dynos (e.g., Performance-M, Performance-L) for more CPU and memory:
heroku dyno:type Performance-M
Be aware that scaling beyond the free tier incurs charges. Monitor usage in the Heroku Dashboard under the Resources tab.
11. Connect a Custom Domain
Heroku provides a default .herokuapp.com domain, but you can connect your own domain (e.g., yourwebsite.com) for production use.
In the Heroku Dashboard, go to your app ? Settings ? Add Domain. Enter your domain name.
Then, configure DNS records with your domain registrar:
- Create a CNAME record pointing to
your-app-name.herokuapp.com - Or, for apex domains (e.g.,
example.com), use ALIAS or ANAME records (if supported), or point to Herokus IP addresses:50.19.84.104,50.19.85.154
Heroku will automatically provision an SSL certificate via Lets Encrypt for your custom domain within minutes.
12. Deploy Updates
Deploying updates is identical to the initial deployment. After making changes locally:
git add .
git commit -m "Update homepage banner"
git push heroku main
Heroku automatically rebuilds and restarts your app. Theres no need to manually restart dynos or trigger buildsGit push is the deployment trigger.
Best Practices
Use Environment Variables for Configuration
Never hardcode secrets, database URLs, or API keys in your source code. Always use environment variables. This practice ensures your code remains secure and portable across environments (development, staging, production).
Store your environment variables in a .env file locally, but never commit it to version control. Add .env to your .gitignore file:
.env
node_modules/
.DS_Store
Use the dotenv package in Node.js or python-dotenv in Python to load these variables locally. Heroku will override them with its own values during deployment.
Keep Dependencies Minimal and Locked
Heroku installs dependencies based on your lockfile (package-lock.json, Pipfile.lock, Gemfile.lock). Always generate and commit these files to ensure reproducible builds.
Regularly update dependencies to patch security vulnerabilities. Use tools like npm audit, pip-audit, or GitHub Dependabot to automate this process.
Use a .gitignore File
Exclude unnecessary files from your repository to reduce build times and avoid exposing sensitive data:
- Node.js:
node_modules/,.env,npm-debug.log - Python:
__pycache__/,.env,.pytest_cache/ - Java:
target/,.gradle/
Enable Herokus Automatic Buildpack Detection
Heroku auto-detects your apps language using buildpacks. Avoid manually setting buildpacks unless necessary. If youre using multiple languages (e.g., React frontend + Node.js backend), use a multi-buildpack setup:
heroku buildpacks:set heroku/nodejs
heroku buildpacks:add heroku/python
Or use a custom buildpack like heroku/multi and define buildpacks in a .buildpacks file in your project root.
Monitor Performance and Logs
Use Herokus built-in metrics and logs to monitor your apps health. Enable Log Drains to send logs to external services like Loggly, Papertrail, or Datadog for advanced analysis.
Set up alerts for high memory usage, long request times, or frequent restarts. These are early indicators of performance bottlenecks or memory leaks.
Use Staging Environments
Create a separate Heroku app for staging (e.g., your-app-staging) to test changes before deploying to production. Use the same codebase but different environment variables.
Deploy to staging with:
git push staging main
Where staging is a remote youve added:
git remote add staging https://git.heroku.com/your-app-staging.git
Optimize Static Assets
For frontend-heavy apps (React, Vue, Angular), build static assets locally and serve them via a static file server. Avoid compiling assets on Heroku during deployment, as it increases build time.
For example, in a React app:
npm run build
heroku config:set NPM_CONFIG_PRODUCTION=true
Then use a simple Express server to serve the build/ folder.
Use Heroku Postgres for Production Data
Heroku Postgres is a managed PostgreSQL database service integrated with Heroku. Its reliable, scalable, and easy to set up. Avoid using SQLite for production appsits not designed for concurrent access and will cause data corruption on Herokus ephemeral filesystem.
Add Heroku Postgres via the CLI:
heroku addons:create heroku-postgresql:hobby-dev
Heroku automatically sets the DATABASE_URL environment variable. Use it in your ORM configuration (e.g., Sequelize, Django, SQLAlchemy).
Set Up Health Checks
Heroku restarts dynos if they dont respond to HTTP requests within a timeout window. Ensure your app has a health check endpoint (e.g., /health) that returns a 200 status quickly:
app.get('/health', (req, res) => {
res.status(200).json({ status: 'OK' });
});
This helps prevent unnecessary restarts during deployment or maintenance.
Use GitHub Integration for Continuous Deployment
Heroku integrates with GitHub to enable automatic deployments on push to a specific branch. Go to your apps Dashboard ? Deploy tab ? Connect to GitHub. Choose your repository and enable automatic deploys.
This is ideal for teams practicing CI/CD. You can also set up manual deploy triggers for staging branches.
Tools and Resources
Heroku Dashboard
The primary interface for managing apps, viewing metrics, adding add-ons, and reviewing logs. Accessible at https://dashboard.heroku.com.
Heroku CLI
The essential command-line tool for deployment, configuration, and monitoring. Download and install from Heroku CLI Documentation.
Heroku Postgres
Managed PostgreSQL database service with automatic backups, monitoring, and scaling. Free tier available. Documentation: Heroku Postgres.
Heroku Redis
Managed Redis instance for caching, sessions, and real-time features. Ideal for applications needing fast data access. Add via: heroku addons:create heroku-redis:hobby-dev.
Log Drains
Forward logs to external services like Papertrail, Loggly, or Datadog for centralized logging and alerting. Configure via:
heroku drains:add https://logs.papertrailapp.com:12345
Heroku Scheduler
Run periodic tasks (e.g., data cleanup, email reports) without needing a background worker. Free tier available. Add via:
heroku addons:create scheduler:standard
Heroku Metrics
View real-time performance data including response time, memory usage, and request queue length under the Resources tab in the dashboard.
Heroku Labs (Experimental Features)
Access experimental features like HTTP/2, dyno metadata, or faster build times via:
heroku labs:enable feature-name
Use with cautionthese features may change or be removed.
Heroku Dev Center
The official documentation hub with guides, tutorials, and troubleshooting articles: https://devcenter.heroku.com.
Heroku Status Page
Check for ongoing platform outages or maintenance: https://status.heroku.com.
Heroku GitHub Actions Integration
Use GitHub Actions to automate testing and deployment to Heroku. Example workflow:
name: Deploy to Heroku
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy to Heroku
uses: akhileshns/heroku-deploy@v3.12.12
with:
heroku_api_key: ${{ secrets.HEROKU_API_KEY }}
heroku_app_name: "your-app-name"
heroku_email: "you@example.com"
buildpack: heroku/nodejs
Real Examples
Example 1: Deploying a Node.js Express App
Project structure:
/my-express-app
??? index.js
??? package.json
??? Procfile
??? .gitignore
index.js:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello from Heroku!');
});
app.listen(port, () => {
console.log(Server running on port ${port});
});
package.json:
{
"name": "my-express-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2"
}
}
Procfile:
web: node index.js
.gitignore:
node_modules/
.env
Deploy steps:
git init
git add .
git commit -m "Initial commit"
heroku create
git push heroku main
Visit the generated URL. Your app is live.
Example 2: Deploying a Python Flask App with PostgreSQL
Project structure:
/my-flask-app
??? app.py
??? requirements.txt
??? Procfile
??? .gitignore
app.py:
from flask import Flask
import os
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello from Flask on Heroku!'
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
requirements.txt:
Flask==2.3.3
gunicorn==21.2.0
Procfile:
web: gunicorn app:app
Deploy:
heroku create
git push heroku main
heroku addons:create heroku-postgresql:hobby-dev
Heroku automatically sets DATABASE_URL. Your app now runs with a persistent database.
Example 3: Deploying a React Frontend with Node.js Backend
Structure:
/my-fullstack-app
??? client/ React app
? ??? package.json
? ??? build/
Built assets
??? server/ Node.js backend
? ??? index.js
? ??? package.json
??? Procfile
??? .gitignore
server/index.js:
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.static(path.join(__dirname, '../client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
});
Build React app locally:
cd client
npm run build
Then deploy the entire folder to Heroku. Heroku will detect Node.js and run the server.
FAQs
Can I deploy a static HTML site to Heroku?
Yes. Create a simple Node.js server using Express to serve static files, or use a buildpack like heroku/buildpack-static. Example Procfile: web: npx serve -s build (if using Create React App).
How much does it cost to deploy on Heroku?
Heroku offers a free tier with 550 free dyno hours per month (enough for one app running 24/7 for ~18 days). Paid plans start at $7/month for a Hobby dyno. Add-ons like databases and Redis have separate pricing.
Why is my app crashing after deployment?
Common causes: missing Procfile, incorrect start command, port not bound to process.env.PORT, or missing environment variables. Check logs with heroku logs --tail.
Can I use Heroku for production apps?
Absolutely. Many startups and small businesses use Heroku in production. For high-traffic applications, consider upgrading to Performance dynos and adding a CDN or load balancer.
Does Heroku support Docker?
Yes. Heroku supports Container Registry for deploying Docker images. Use heroku container:login and heroku container:push web to deploy custom containers.
How do I rollback a deployment?
Use: heroku releases to view deployment history, then heroku rollback vXX to revert to a previous release.
Is Heroku secure?
Heroku provides SSL by default, secure network isolation, and regular infrastructure updates. However, security depends on your apps codealways validate inputs, sanitize data, and use environment variables for secrets.
Can I connect a custom database like MongoDB or MySQL?
Yes. Use third-party add-ons like MongoDB Atlas, ClearDB, or ElephantSQL. Set the connection string as an environment variable.
What happens if I exceed my free dyno hours?
Your app will sleep and become inaccessible until the next billing cycle or until you upgrade. Youll receive email notifications before this happens.
How do I delete a Heroku app?
From the Dashboard: go to your app ? Settings ? Scroll to bottom ? Delete App. Confirm by typing the app name.
Conclusion
Deploying to Heroku is one of the most straightforward ways to get your application live on the internet. Its intuitive interface, seamless Git integration, and robust ecosystem of add-ons make it an ideal platform for developers at any level. Whether youre building a simple portfolio site or a scalable web service, Heroku removes the friction of infrastructure management so you can focus on what matters: your code.
This guide walked you through the entire deployment processfrom account creation and app setup to advanced configuration and real-world examples. We covered best practices for security, performance, and maintainability, and introduced essential tools to enhance your workflow.
Remember: Heroku is not a one-size-fits-all solution. For large-scale applications with complex infrastructure needs, platforms like AWS, Google Cloud, or Azure may offer more control and cost efficiency. But for rapid iteration, prototyping, and small-to-medium applications, Heroku remains unmatched in ease of use and reliability.
Now that you know how to deploy to Heroku, experiment with different frameworks, connect databases, add custom domains, and automate deployments. The next step is yoursdeploy your first app today, and keep building.