3 Ways to Run Laravel on a Custom Port

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

Running Laravel on a custom port can be an essential task when you are working with multiple applications, or when the default port 8000 is already in use. Laravel, a popular PHP framework for web development, provides an easy-to-use serving mechanism, but developers might need more flexibility. Below, we explore several solutions to run Laravel on a custom port.

Solution 1: Using the PHP Artisan Serve Command

The simplest way to run Laravel on a custom port is to use the in-built Artisan command with the --port option.

  • Step 1: Open your terminal or command prompt.
  • Step 2: Navigate to your Laravel project directory.
  • Step 3: Run the following command php artisan serve --port=8080

Output: Laravel development server started: <http://127.0.0.1:8080>

This solution is quick and does not require any additional configuration. However, it is suitable for development purposes only and not recommended for production environments.

Solution 2: Modifying the Web Server Configuration

For a more persistent and environment-specific setup, you can modify the configuration of your web server, such as Nginx or Apache.

  • Step 1: Locate your web server’s configuration file for the Laravel site.
  • Step 2: Update the listen directive to your desired port, such as listen 8080; for Nginx or Listen 8080 for Apache.
  • Step 3: Reload or restart your web server to apply the changes.

No specific Laravel code modification is needed for this solution. The web server directly handles requests on the custom port. It is a robust solution but requires server access and administrative privileges.

Solution 3: Using a Docker Container

Running Laravel in a Docker container can give you the flexibility to set any port mapping you prefer.

  • Step 1: Create a Dockerfile in your Laravel project if you don’t already have one.
  • Step 2: Build your Docker image with docker build -t laravel-image .
  • Step 3: Run your Docker container mapping your custom port with docker run -p 8080:80 laravel-image.

Docker configuration and commands are all that are required to implement this solution. This approach is scalable and encapsulates the environment but requires Docker knowledge and additional resources.

Conclusion

Each solution to running Laravel on a custom port has its context and use cases. The Artisan serve command is excellent for quick, temporary development scenarios. Modifying the web server configuration is beneficial for more permanent setups. Using Docker containers gives you portability and environment consistency. Depending on your working environment and requirements, you can choose the solution that best fits your needs.