How to run Symfony on a custom port

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

Introduction

Running Symfony on a custom port is an essential skill for developers who want to customize their Symfony application’s development environment. By default, Symfony web server runs on port 8000, but there can be instances when running it on a different port is necessary, such as avoiding port conflicts or simulating production environments. In this tutorial, we’ll explore how you can configure your Symfony application to run on a custom port.

Prerequisites:

  • A Symfony project
  • PHP 7.1.3 or higher installed
  • Composer
  • Basic knowledge of Symfony and the command line

Using the Symfony Local Web Server

One of the simplest ways to run Symfony on a custom port is by using the Symfony local web server. This server provides a powerful and flexible way to manage your Symfony application during development.

$ symfony server:start --port=8080

This command will start the Symfony server on port 8080. You should see an output similar to: [OK] Server listening on http://127.0.0.1:8080

Setting a Custom Port with PHP Built-in Server

If you don’t have the Symfony server installed, you can use PHP’s built-in server. Here is how you can specify a custom port:

$ php -S 127.0.0.1:8080 -t public

This command runs the built-in PHP server on port 8080, with the document root set to the public directory of your Symfony project.

Automating with a Script

To avoid typing the command each time, you can create a script in your composer.json file:

"scripts": {
   "start-server": "php -S 127.0.0.1:8080 -t public"
}

Now you can start the server with:

$ composer start-server

The output will indicate that the server is running on the custom port.

Working with Docker Containers

If you’re working with Docker, you can specify a custom port via your docker-compose.yml. version: ‘3.7’ services: web: image: ‘symfony:web’ ports: – ‘8080:80’

This snippet maps the host’s port 8080 to the container’s port 80, where your Symfony app is served. Run your container:

$ docker-compose up -d

Your Symfony app is now accessible on port 8080.

Overriding the Default Web Server Port Configuration

You can modify your Symfony app’s web server configuration located in the application’s .env file:

# .env
...
APP_PORT=8080
...

Note that changing the environment variable APP_PORT assumes your web server or PHP built-in server supports this and that you’ve programmed them to respect this variable.

Conclusion

In this tutorial, we’ve looked at several ways to run a Symfony application on a custom port, from using the Symfony server to leveraging Docker. Each method provides flexibility depending on your working environment and development preferences. It’s essential to understand these techniques to ensure that your project is accessible and works on different environments smoothly.