Set a better Web server in PHP up¶
This is a follow-up tutorial for the Create a simple CRUD in PHP tutorial.
The code of this tutorial is available on GitHub.
Objectives¶
With this tutorial, you will be able to test new ways of running a Web server locally and for production.
Prerequisites¶
- Docker must be installed.
- Docker Compose must be installed (it should be installed by default with Docker in most cases).
- Visual Studio Code must be installed.
- Dev containers must be installed in Visual Studio Code.
Steps¶
Open the "Create a simple CRUD in PHP" repository¶
Set the project up¶
Open the devcontainer by clicking on the bottom left corner of Visual Studio Code and selecting "Remote-Containers: Reopen in Container".
Wait for the container to be built and the project to be opened.
Open a terminal in Visual Studio Code and run the following command:
Open your browser and go to http://localhost:8081. You should see the phpMyAdmin interface.
Enter the following credentials:
- Server: db
- Username: user
- Password: password
Click on "Go".
In the database list, you should see the products_crud
database. Select it.
Create a new table named products
with the following 5 columns:
- id: int(11) - Primary - Auto Increment
- title: varchar(512)
- description: longtext - Null
- price: decimal(10,2)
- create_date: datetime
Ok, the table is created. Now, let's create a new product.
Click on the "SQL" tab.
Enter the following SQL query:
Click on "Go".
Go back to the "Browse" tab. You should see the 2 products you just created.
Ok, now that we have a database with some data, let's see how we can run the project.
Open a new terminal in Visual Studio Code and run the following command:
Open your browser and go to http://localhost:8080. You should see the list of products.
Use a containerized Web server¶
Stop the Web server by pressing Ctrl + C
in the terminal.
Modify the docker-compose.yml
file to add a new service named web
:
Add a folder www
to your project, and move all the .php
and the .css
files in it.
Your project should look like this:
Make it work !¶
Run the following command to start the containers:
Open your browser and go to http://localhost:41062/www/. You should see the list of products.
Oh no !
An error is displayed:
The database is not accessible from the container. As every container was created in the same network, we can use the name of the service as the host.
Change all the 127.0.0.1
to db
in the .php
files.
Refresh the page. You should see the list of products.
Conclusion¶
You know how to set a simple web server up ! And you can reproduce every step of this tutorial with any PHP project.