Use Docker to run PostgreSQL without local installation by starting a container with the official image, setting password, port, and volume for persistence. 2. Create a named volume postgres-data to preserve data across container restarts. 3. Customize database name and user via environment variables POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB. 4. Connect using psql inside the container or external clients like pgAdmin at localhost:5432.
To set up a PostgreSQL database using Docker, you don't need to install PostgreSQL directly on your machine. Docker simplifies the process by containerizing the database, making it portable and easy to manage. The key is to run a PostgreSQL container with proper configuration for passwords, ports, and persistent storage.
Run PostgreSQL in a Docker Container
Use the official PostgreSQL image from Docker Hub to start a container. At minimum, you need to set a password for the default postgres user and expose the database port.
- Run this command to start a PostgreSQL container:
docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres
- --name my-postgres: Assigns a name to the container for easier management.
- -e POSTGRES_PASSWORD=...: Sets the password for the default superuser.
- -p 5432:5432: Maps host port 5432 to container port 5432.
- -d postgres: Runs the official PostgreSQL image in detached mode.
Add Persistent Data Storage
By default, data is lost when the container stops. To preserve your data, use a Docker volume.
- Create a named volume for data persistence:
docker volume create postgres-data
docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v postgres-data:/var/lib/postgresql/data -d postgres
- -v postgres-data:/var/lib/postgresql/data: Mounts the volume to the directory where PostgreSQL stores data.
Customize Database Name and User
You can define a custom database and user during startup using environment variables.
- Set POSTGRES_DB to specify the default database name.
- Set POSTGRES_USER to create a custom user.
Example command:
docker run --name my-postgres \
-e POSTGRES_USER=admin \
-e POSTGRES_PASSWORD=adminpass \
-e POSTGRES_DB=myapp_db \
-p 5432:5432 \
-v postgres-data:/var/lib/postgresql/data \
-d postgres
Connect to the PostgreSQL Database
Once the container is running, connect using psql or any PostgreSQL client.
- Access the container's psql shell:
docker exec -it my-postgres psql -U admin -d myapp_db
- From the host machine, use tools like pgAdmin, DBeaver, or code (e.g., Python with psycopg2) to connect to localhost:5432.
Basically just run the container with the right environment variables and a volume. That way you get a working, persistent PostgreSQL setup in minutes.
The above is the detailed content of How to set up a PostgreSQL database using Docker?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction

Building an independent PHP task container environment can be implemented through Docker. The specific steps are as follows: 1. Install Docker and DockerCompose as the basis; 2. Create an independent directory to store Dockerfile and crontab files; 3. Write Dockerfile to define the PHPCLI environment and install cron and necessary extensions; 4. Write a crontab file to define timing tasks; 5. Write a docker-compose.yml mount script directory and configure environment variables; 6. Start the container and verify the log. Compared with performing timing tasks in web containers, independent containers have the advantages of resource isolation, pure environment, strong stability, and easy expansion. To ensure logging and error capture

Uninstall the old version of Docker to avoid conflicts, 2. Install yum-utils and add the official Docker repository, 3. Install DockerCE, CLI and containerd, 4. Start and enable Docker services, 5. Run hello-world image to verify that the installation is successful, 6. Optionally configure non-root users to run Docker.

DockerforWindowsusesaLinuxVMorWSL2toruncontainersbecauseWindowslacksnativeLinuxkernelfeatures;1)itautomaticallymanagesalightweightLinuxVM(orusesWSL2)withHyper-VtohosttheDockerdaemonandcontainers;2)theDockerCLIandDesktopinterfaceforwardcommandstotheda

Dockerisaplatformforpackaging,shipping,andrunningapplicationsinlightweight,isolatedcontainersthatsharethehostOSkernel,unlikevirtualmachines.2.InstallDockerDesktoponWindowsormacOS,orusethecurlcommandonLinux,thentestwithdocker--versionanddockerrunhello

DanglingimagesareuntaggedlayersnotassociatedwithanycontainerandcanberemovedusingDocker’sbuilt-incommands.1.Usedockerimageprunetosafelyremovedanglingimagesafterconfirmation,oradd-ftoforceremovalwithoutprompt.2.Usedockerimageprune-atoalsoremoveallunuse
