• Cloud Computing
  • Amazon Web Services
  • Microsoft Azure
  • Google Cloud Platform
  • Operating System
  • Computer Network

assign ip docker container

  • Explore Our Geeks Community
  • Introduction to Docker
  • Features of Docker
  • Architecture of Docker
  • What is Docker Hub?
  • What is Docker Cloud?

Docker Installation

  • Docker - Installation on Windows
  • How to Install Docker using Chocolatey on Windows?
  • How To Install and Configure Docker in Ubuntu?
  • How to Install Docker on MacOS?
  • How to install and configure Docker on Arch-based Linux Distributions(Manjaro) ?
  • How to Install Docker-CE in Redhat 8?
  • Docker Commands
  • Running Commands Inside Docker Container
  • Docker - USER Instruction

Docker Images

  • What is Docker Images?
  • Working with Docker Images
  • Docker - Publishing Images to Docker Hub
  • How to commit your own Docker Customized Image from container?
  • Docker - Using Image Tags
  • Next.js Docker Images
  • How to Use Local Docker Images With Minikube?

Docker Containers

  • Containerization using Docker
  • Virtualisation with Docker Containers
  • Docker - Docker Container for Node.js
  • Remove All Containers and Images in Docker
  • How to Push a Container Image to a Docker Repository?
  • Docker - Container Linking
  • Tips to Manage Docker Containers using CLI
  • Mounting a Volume Inside Docker Container
  • Difference between Docker Image and Container
  • Difference between Virtual Machines and Containers
  • How to Install Linux Packages Inside a Docker Container?
  • Copying Files to and from Docker Containers
  • How to Run MongoDB as a Docker Container?
  • Docker - Container for NGINX

How to Provide the Static IP to a Docker Container?

Docker compose.

  • Docker - Compose
  • Docker compose tool to run multi container applications

Docker Swarm

  • Introduction to Docker Swarm Mode
  • Difference between Kubernetes and Docker Swarm
  • Docker Networking
  • Docker - Managing Ports
  • Creating a Network in Docker and Connecting a Container to That Network
  • Connecting Two Docker Containers Over the Same Network
  • How to use Docker Default Bridge Networking?
  • Create your own secure Home Network using Pi-hole and Docker

Docker Registry

  • What is Docker Registry?
  • Docker - Using Public Repositories To Host Docker Images
  • Docker - Private Registries
  • Creating a Private Repository and Push an Image to That Private Repository

Docker is an open-source project that makes it easier to create, deploy and run applications. It provides a lightweight environment to run your applications. It is a tool that makes an isolated environment inside your computer. Think of Docker as your private room in your house. Living with your family, you have to share a TV, table, chair and so on. Once you get into your room, all are yours. You don’t have to share them, and feel private, though your family may listen to your voice and tell you to be calm. Docker is like your room. Docker can be private from the host computer, though in some parts it is monitored and controlled by the host.

Let’s Come to Our Problem statement: We Want to Create a Docker Container with Static IP.

Let’s Say We have configured our Server and Connected with CICD tools which Update the Application and Relaunch our Complete Docker Environment But as the New Environment is Created Which lead to change the IP definitely But Our Use Case is that We Don’t Want to Change Because Might be that some other application depends on it and if the IP changed then that application Stop Working.

Step 1: Configure the Docker in the Server

assign ip docker container

Installation of Docker

assign ip docker container

Pulling the Latest Nginx Image

assign ip docker container

Show the Images

Step 2:   Create a Network with Subnet (CIDR).

assign ip docker container

Creating Network 

assign ip docker container

List the Network

Step 3: Deploy the Container this Network with your Custom Static IP

  • Network Name (Which You at the time of Creation Of Network)

assign ip docker container

Inspect Container And Check the Network

assign ip docker container

Container with Static IP Address

Please Login to comment...

Similar read thumbnail

  • TrueGeek-2021

Please write us at contrib[email protected] to report any issue with the above content

Improve your Coding Skills with Practice

 alt=

docker network connect

Connect a container to a network

Description

Connects a container to a network. You can connect a container by name or by ID. Once connected, the container can communicate with other containers in the same network.

Connect a running container to a network

Connect a container to a network when it starts.

You can also use the docker run --network=<network-name> option to start a container and immediately connect it to a network.

Specify the IP address a container will use on a given network (--ip)

You can specify the IP address you want to be assigned to the container's interface.

Use the legacy --link option (--link)

You can use --link option to link another container with a preferred alias

Create a network alias for a container (--alias)

--alias option can be used to resolve the container by another name in the network being connected to.

Network implications of stopping, pausing, or restarting containers

You can pause, restart, and stop containers that are connected to a network. A container connects to its configured networks when it runs.

If specified, the container's IP address(es) is reapplied when a stopped container is restarted. If the IP address is no longer available, the container fails to start. One way to guarantee that the IP address is available is to specify an --ip-range when creating the network, and choose the static IP address(es) from outside that range. This ensures that the IP address is not given to another container while this container is not on the network.

To verify the container is connected, use the docker network inspect command. Use docker network disconnect to remove a container from the network.

Once connected in network, containers can communicate using only another container's IP address or name. For overlay networks or custom plugins that support multi-host connectivity, containers connected to the same multi-host network but launched from different Engines can also communicate in this way.

You can connect a container to one or more networks. The networks need not be the same type. For example, you can connect a single container bridge and overlay networks.

How to Get A Docker Container IP Address - Explained with Examples

Docker provides the ability to package and run an application in a loosely isolated environment called a container.

I know what you might be thinking – come on, not another post explaining what Docker is, it's everywhere these days!

docker-i-see

But don't worry, we are skipping that basic introduction. The target audience for this article should already have a basic understanding of what Docker and Containers are.

But have you ever wondered how to get a Docker Container IP Address?

Docker network explained

First, let's understand how the Docker network works. For that we are going to focus on the default bridge network. When you are using Docker, if you don’t specify a driver this is the type of network you are using.

docker-network

The bridge network works as a private network internal to the host so containers on it can communicate. External access is granted by exposing ports to containers.

Bridge networks are used when your applications run in standalone containers that need to communicate.

In the picture above db and web can communicate with each other on a user created bridge network called mybridge .

If you’ve never added a network in Docker you should see something similar to this:

The default bridge network is listed, along with host and none .  We will ignore the other two, and use the bridge network when we get to the examples.

Docker Container IP Address

By default, the container is assigned an IP address for every Docker network it connects to. And each network is created with a default subnet mask, using it as a pool later on to give away the IP addresses.

Usually Docker uses the default 172.17. 0.0/16 subnet for container networking.

Now to better understand it, we will execute a real use case.

drawing

Docker Example

To illustrate this, we will use a Hive and Hadoop environment, containing 5 Docker Containers.

Check out the docker-compose.yml file we are about to execute:

From docker-hive GitHub

No one wants to read a HUGE config file, right? So here's a picture:

Screen-Shot-2020-06-21-at-2.48.18-PM

Much better! Now let's start up those containers:

We can see 5 containers:

Next let's check our Docker networks:

Wait a minute... there's a new network called docker-hive_default !

By default docker compose sets up a single network for your app. And your app’s network is given a name based on the “project name”, originated from the name of the directory it lives in.

So since our directory is named docker-hive , this explains the new network.

Next some examples on how to get the Docker IP Address.

How to Get A Docker Container IP Address - examples

And now that I have your attention, we are going to unveil the mystery.

drawing

1. Using Docker Inspect

Docker inspect is a great way to retrieve low-level information on Docker objects. You can pick out any field from the returned JSON in a fairly straightforward manner.

So shall we use it to get the IP Address from the dockerhive_datanode ?

Didn't you say that Docker uses the default 172.17. 0.0/16 subnet for container networking? Why is the returned IP Address: 172.18.0.5  outside it?

Screen-Shot-2020-06-22-at-3.25.07-PM

To answer that we have to look at our network settings:

We executed this example in a Compute Engine VM, and in this test, the docker network was assigned a different subnet: 172.18.0.0/16 . That explains it!

Furthermore, we can also lookup all IP Addresses inside the docker-hive_default network.

So we don't need to look up each Container's IP individually:

drawing

If you didn't notice, we used jq help to parse the Containers map object.

2. Using Docker exec

In the following example we will work with the dockerhive_namenode .

3. Inside the Docker Container

We can even find other containers' IP Addresses that are inside a container in the same network:

Hive mestastore

Hive server

All examples were executed in a linux distribution Compute Engine VM. If you execute them in macOS or Windows environments the sample commands might change a bit.

Also bear in mind that those IP Addresses in the examples given are internal to the sample docker-hive_default network. So if you have a use case to connect to those containers externally, you would need to use the host machine's external IP (assuming that you are exposing the containers ports correctly). Or if you are using kubernetes, for instance, to manage your Docker containers, let it handle the IP Addresses for you kubernetes-expose-external-ip-address ?.

* Illustrations from icons8.com by Murat Kalkavan .

?☁️ Senior Software Engineer | ♥️ Open Source | 5x GCP certified | DevOps | Data Engineer | Cloud Architect | CI&T

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Is it possible to assign the host's IP address to a docker container running within it?

I am a total newbie to Docker and while I understand the difference between a container and a VM, I am not sure whether it is possible to assign the host's IP address (the 192.168.x.x one, not the 127.0.0.1) to a docker container running within it.

I found a great answer that explains how to connect to the host from within the container . But it doesn't state whether both host and container having the same IP address is possible at all.

Also, this question about Docker in a Windows environment.

  • docker-for-windows

WebViewer's user avatar

  • 2 192.168.X.X isn’t accessible outside your network you do realize that? –  Ramhound Nov 23, 2022 at 17:04
  • 3 What are you trying to achieve? –  gronostaj Nov 23, 2022 at 18:45
  • 1 Why is the "same exact IP and hostname" aspect important? ( XY problem ) –  gronostaj Nov 24, 2022 at 7:05
  • 1 Also, no, on Windows this is entirely impossible. –  Daniel B Nov 24, 2022 at 10:01
  • 2 @gronostaj Yes, it does that. I was referring to the original question, with Docker sort-of impersonating the host on the network. Host network mode is not available on Windows due to technical restrictions. –  Daniel B Nov 24, 2022 at 15:17

Based on your comment explaining what you're trying to achieve:

Actual hostname and IP of your containers doesn't matter. You only have to ensure that the domain name is resolved to something (physical host or a container) that runs the web server (Apache/nginx/…) on port 80. Since domain is getting resolved to your host, you only need to expose dockerized web server's port 80 as host's port. Docker supports this by the means of port publishing which is enabled using the -p option of docker run .

Presumably you want to run the DB, web server and PHP in separate containers. The most convenient way to automate this is to use docker-compose . Port publishing can be achieved using the ports option. There are many tutorials all over the web on how to achieve this.

gronostaj's user avatar

  • Thank you @gronostaj. In the proposed solution, will the web server's hostname part in the URL be the same as my Windows laptop's hostname? (by "hostname part", I mean 'mywindowslaptop' in ' mywindowslaptop/wordpress' ). –  WebViewer Nov 24, 2022 at 15:37
  • @WebViewer No, but that doesn't matter. Your hosts file resolves that domain name to your host, so the browsers trying to load resources from it will talk to your host. As long as the website is reachable on your host's port 80, it will work. (If your links use HTTPS, you'll have to publish port 443 too and you'll be getting certificate errors which you'll have to ignore) –  gronostaj Nov 24, 2022 at 15:50
  • @WebViewer You seem to have two misconceptions: 1) that DNS will only resolve a domain name to a host if its hostname matches the domain name; 2) that if multiple hosts have the same hostname, the client will somehow always talk to the "right" one –  gronostaj Nov 24, 2022 at 16:31

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged docker-for-windows ..

  • Featured on Meta
  • Update: New Colors Launched
  • Incident update and uptime reporting

Hot Network Questions

  • What are the rights of the school to deny my use of my own laptop?
  • Does the atmospheric pressure of Mars fluctuate because of the seasonal evaporation of the polar ice caps?
  • Can a surrogate be guilty of kidnapping?
  • Philosophy behind sigma: is it measurement error?
  • Why did I still have power after a tree cut the neutral wire leading to the transformer?
  • Apollo 13's plutonium RTG re-entry into the Tonga Trench: Good shootin' or good luck?
  • Did Hamas dig up EU-funded water pipes and turn them into rockets?
  • Which protocol to send the most possible data through satellite?
  • Did the U.S. ever decide to not protect Israel at the U.N. or other international bodies?
  • How can I receive money without giving away my identity?
  • What is the origin of the default 256-color VGA palette?
  • Can't compile latex3 regexp
  • What is the origin of the verb 'foxed' in reference to book condition?
  • Can a warforged become a vampire?
  • What was the first laptop to support two external monitors?
  • What are better ways of indicating "insert actual value in place of the placeholder value" in documentation?
  • Falsifiability of Assumptions
  • What is the correct translation of "Venetiarum" in this context?
  • Does "risk score" always have to be a numerical value?
  • 1 to 10 vs 1 through 10 - How to include the end values
  • What is the e visa site for Turkey? (2023)
  • Did any Muslim country officially express disagreement over America's plan to have the Palestinian Authority govern over the Gaza Strip?
  • According to the basic principles of UI Design, which alignment works the best as shown in the following picture
  • Cause-effect definition of fictitious forces

assign ip docker container

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Assign static IP to a Docker container

There are two types of static IPs, public and private IP addresses. We all know the public IP Docker mapping by now, using Nginx and port mapping. Today we are going to see how can we assign a private IP address to a Docker container.

Prerequisites

Using docker compose, using docker cli.

Step 1 . Create a network first.

Step 2 . Spin up a container.

Step 3 . Verify the IP address assignment.

Using a private static IP address for a Docker container is not a good practice at all, but it could help you with debugging a local development environment stack. Although this is a hack around, always make sure to use the service name as part of the service endpoint reference. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram .

Let's keep in touch

Subscribe to keep up with fresh news. We promise not to share your email address nor spam you!

Default list

How-To Geek

How to run multiple docker containers on different ip addresses.

Docker makes it easy to run apps using serverless cloud solutions, but many people will prefer to manage multiple containers running on a few powerful machines.

Quick Links

How do network interfaces work.

  • Running Multiple Docker Services on the Same Server

How Do You Get Multiple IP Addresses?

Docker makes it easy to run apps using serverless cloud solutions, but many people will prefer to manage multiple containers running on a few powerful machines. In this case, using multiple IP addresses can be a great way to manage multiple services on the same port.

Linux uses network interfaces to represent physical hardware, as well as creating virtual networking components like VLANs, bridging, or aliases. If you list all the devices on your system with

, you'll find various interfaces like

 which represent actual connections.

IP addresses are a separate system from network interfaces, but essentially, you can have multiple IP addresses configured on a single interface, allowing you to bind services to network sockets for each

 combination.

This works well with Docker , which lets you handle the networking at the Docker level instead of the application level. With Docker, the application inside the container can just bind to "port 80," which gets mapped by Docker to a specific IP address on the host.

This makes it far easier to separate the application layer from the host that's running it. For example, you could have multiple different API services all running on the same machine, without configuring the underlying containers.

It doesn't really matter for Docker which system interface the IP address is on, as Docker's internal networking will handle this for you, as long as you launch the containers with the correct configuration.

Running Multiple Docker  Services on the Same Server

Running a container on a specific address is pretty easy, depending on how you launch it. Essentially, most Docker containers have their ports configured with the

 format. For example,

 would take the container's port 80 and make it available from the host's port 5000.

However, you can actually bind sockets directly, meaning instead of

, you can substitute an

 pair, using three colons for the entire binding:

docker run -it -d ipaddress:hostport:containerport --name web nginx

So, for example, you could have two NGINX containers on different IPs, like so (keep in mind, Docker needs separate container names):

docker run -it -d 123.0.0.1:80:80 --name web nginx

docker run -it -d 123.0.0.2:80:80 --name web2 nginx

If you're using Docker Compose, the configuration is similar. In the ports  section for the service, you can use the same syntax to bind to particular addresses.

version: "3"

image: nginx

restart: always

- "123.0.0.1:80:80"

In either case, you can create multiple services bound to host port 80, as long as the services don't listen on the same IP addresses.

If you are doing this, however, you will want to make sure that no container is listening on just the port---this will be a misconfiguration, as omitting the IP address will mean that it will listen on all addresses for that interface.

Most servers come with only a single IP address, so you may have to set up additional ones yourself.

Setting up multiple IPs per server will depend on the host you're using. For example, AWS has it's "Elastic IP" service, which is free to use if you're using one IP per machine. However, if you want to purchase additional Elastic IP addresses, you can associate them with any server. You will pay $3.65 a month for each one .

Some services will allow you to make a one-time purchase of IP addresses, like OVH, which allows purchases of blocks up to /24 in size.

If you want to purchase large, contiguous blocks of IP address for you to actually own, you can do so through various brokerages, though this generally incurs a large fee and is mostly for large organizations.

Once you have the IP addresses, it's up to your cloud provider to point them to your address. However, it's up to you to configure your network interface to use it, using a tool like netplan .

Assign Public IP Address to Docker Container without Port Binding

MACVLAN creates multiple virtual network interfaces with different MAC addresses. This way if your system has multiple IP addresses with MAC addresses then we can create multiple virtual network interfaces each having their own IP address and MAC address.

MACVLAN doesn’t need to learn(identify) mac addresses of the systems within the network to distribute traffic as it knows every mac address, this makes it fast and easy to setup than bridge type networking.

Problems with docker containers port binding:

  • If a container uses port 8000 of host then no other containers can use that port.
  • Binding multiple ports to container can be done by specifying port range but this operation takes more time depending on no. of ports to bind.
  • IPTables rules become cumbersome as no. of bindings increase.

Advantages of MACVLAN:

  • IPTables aren’t affected.
  • No port binding.
  • Easy to setup.
  • Faster than bridge networking.

Creating MACVLAN network:

Host IP: 188.40.102.103

Host subnet: 188.40.76.0

Host Mask: 26

Host gateway: 188.40.76.1

Host ethernet interface: eth0

Above command creates network named ‘macvlan_bridge’

Running a container using ‘macvlan_bridge’ network:

Host contains multiple publicly accessible IP addresses with MAC addresses.

Host additional IP/MAC: 88.99.102.115/00:50:56:00:60:42

Above command runs nginx container with ip ‘88.99.102.115’ attached to this container, you can verify by hitting ‘88.99.102.115’ where you will be welcomed with nginx page.

This way overall network setup will become clear and easy to handle.

  • Privacy Policy
  • Terms and Conditions

How to Assign Static IP Addresses to Docker Compose Containers

How to Assign Static IP Addresses to Docker Compose Containers

When we start Docker containers with Docker Compose, all the service containers in it will get dynamically assigned IP addresses. For example, if you run the containers in the below docker-compose.yml file, each of its app service containers can get new or random IP addresses from its default network. This dynamic IP behaviour is not a problem for containers in the same docker-compose.yml file as they can resolve hostnames out of the box. But the problem is, when you wanted to connect to these containers from the host PC or any other external network, it will be fairly difficult to determine the exact IP address as they do not have any static IP addresses.

Under that kind of situation, we can assign static IP addresses to Docker Compose service containers so they will always get the exact same IP address. For that, first, we must add a custom network to the docker-compose.yml file. Make sure to mention an unused subnet or otherwise, you will not be able to start containers.

Then, mention that network (Ex: appNetwork) for each service container that needs a static IP address. Also, make sure to double-check whether the IP address that you are going to assign is in the range of the subnet.

Likewise, if you need, you can mention IPv6 addresses with ipv6_address as well.

Ultimately, the final docker-compose.yml file should look like something similar to the following.

Now you can start containers using the docker-compose up command. Add the -d flag if you need to start containers in the detached (background) mode.

  • How to Set Timezone in Linux Docker Images
  • How to Build Docker Images With Custom Dockerfile Names
  • How to Copy Files Quickly in Docker Images to Host
  • How to Fix "bash: ifconfig: command not found" in Ubuntu Docker Containers
  • Voice &Video
  • Programmable Voice
  • Programmable Video
  • Elastic SIP Trunking
  • Network Traversal
  • Programmable SMS
  • Programmable Chat
  • Authentication
  • Connectivity
  • Phone Numbers
  • Programmable Wireless
  • Marketplace
  • Add‑ons
  • Enterprise Plan
  • Interconnect
  • Access Security
  • Call & Text Marketing
  • Collaboration
  • Commerce Communications
  • Contact Center
  • Customer Stories
  • Partner Showcase
  • Why Twilio?
  • Support Plans
  • API & Docs
  • Jobs at Twilio

You may unsubscribe at any time using the unsubscribe link in the digest email. See our privacy policy for more information.

assign ip docker container

Deep Dive into Laravel Development with Docker

assign ip docker container

Docker is a versatile containerization tool that simplifies the management of the essential components that power your web application. What's more, it saves you the stress of grappling with various independent tools and configurations.

In this article, we will explore how Docker can be used in Laravel development to:

  • Streamline the process of serving your Laravel applications locally
  • Migrate Laravel applications across different computers or servers
  • Eliminate software compatibility concerns
  • Deploy an application to a remote server

Before we delve deeper though, it's important to note that within the Laravel development ecosystem, Laravel Sail serves as the standard for Docker integration. Sail simplifies the process of working with Docker in Laravel, offering a user-friendly approach for developers — especially those without prior Docker experience.

However, in this tutorial, you will get an in-depth exploration of Docker — in the context of Laravel. Then, rather than relying on Laravel Sail's pre-configured environment, you will learn how to run Laravel inside a Docker and deploy it with Docker Compose.

This deeper dive will enhance your understanding of how Laravel Sail works under the hood, empowering you to not only leverage its advantages, but also troubleshoot any potential issues that may arise during usage, or when making custom configurations with Sail.

By the end of this tutorial, you should be able to use Docker to assemble your Laravel application like a well-organized LEGO set, allowing you to construct and operate it seamlessly.

Prerequisites

  • A Digital Ocean account
  • Docker Engine
  • Docker Compose
  • Composer installed globally
  • Prior experience with Laravel development would be ideal, but not mandatory

What is Docker?

Imagine you're making a cake. Instead of baking it in your own kitchen, you use a special portable kitchen. This portable kitchen has everything you need – ingredients, an oven, mixing bowls, etc.

This is like a Docker image. It's a self-contained environment that holds everything your Laravel app needs to run – the code, the supporting files, and the command line tools, etc. It keeps everything organized and separate from your computer's setup, just like the portable kitchen keeps your cake-making separate from your home kitchen. This makes it super easy to move your app between different computers or servers without worrying if they have the right software installed.

Key Docker terms

Now, let's cover a few of the key Docker terms that you need to be familiar with.

Image: Think of an image as a blueprint for what your application needs, much like a recipe guiding Docker in creating a specific environment for your Laravel app. An image includes your code, the web server, and any required tools. These images are akin to ready-to-bake cake mixes, waiting to be transformed into containers at runtime.

Container: A container is analogous to the actual cake baked from the recipe (image). They represent isolated virtual environments where your Laravel application operates, shielded from external influences. Multiple containers are often used simultaneously, each hosting different components of the application, such as the application's database, web server, and caching server.

Dockerfile: Think of a Dockerfile as a set of step-by-step instructions for Docker to build an image. It's akin to documenting the process of mixing ingredients and baking a cake. Within a Dockerfile, you define your app's requirements, such as the PHP version, necessary packages, configuration settings, and environment variables.

Docker Compose: Docker Compose is a tool that simplifies the management of multiple Docker containers by allowing you to define, configure, and run them as a single application, streamlining complex deployments and ensuring seamless communication between containers.

Why should you use Docker?

There are three great reasons for using Docker:

  • Development : Docker gives you a consistent environment across all developers' machines. No more " It works on my machine " issues! Everyone uses the same setup, so the code behaves the same for everyone. Plus, you can quickly start and stop containers as you work on different parts of your app.
  • Testing: With Docker, you can create an image that mirrors your production server. This means you can test your app in an environment that's identical to where it will actually run. Bugs and issues are easier to catch before they reach users.
  • Deployment: Docker containers can be easily moved from one host to another. So, the setup that worked on your local development machine will work on the deployment server too. You package everything neatly into an image, which you can then deploy to your production server. This consistency reduces deployment problems.

Dockerize a Laravel application

With all this said, let’s create and configure a Laravel application powered by Docker. First, create a new Laravel project using Composer, and change into the new project directory with the commands below.

Then, open .env in your preferred text editor or IDE and make the following three changes:

  • Set DB_HOST to database . This needs to match the hostname of the container containing the database.
  • Set DB_USERNAME to laravel . It's best to use an account other than root to connect to a database.
  • Set a value for DB_PASSWORD

Laravel applications require multiple services to function. Let's create the default Docker C ompose configuration file, to define the services required by our Laravel application. The file will contain settings applicable whether the application is running locally or in production. The environment-specific settings will be added in additional configuration files.

In the root of your Laravel application create a new file named docker-compose.yaml , like so:

If you're using Microsoft Windows, or would just prefer to, create the file with your preferred text editor or IDE.

In this file, we will define all the services needed for our Laravel application to function. We can start and stop these services using Docker Compose. Let's get started by defining our database service.

Let’s talk a little about some of the configuration above:

  • image: This points to the base image that this image will be built from. Specifically it will use the official Docker Hub MySQL image .
  • ports: Here, we are defining the port mappings between our local development machine and the Docker container (or between the host and the guest). The port on the left is the port of the local machine while the port on the right is the port on the container.
  • environment: This is where we specify the database credentials needed to connect our Laravel application to the mysql server container. These are assigned from environment variables of the same name in the environment where the container is started, from the .env file of our Laravel application.
  • healthcheck: This ensures the database container is fully started , not just running. If not, the PHP container will not be able to run the database migrations when it starts up.
  • volumes: Docker Volumes make it possible to persist data. Here, we assigned a volume where the changes would be stored, on the local filesystem.

Next, we need to create a Redis service. Add the following after the database service in docker-compose.yml ,:

Similar to the database service, the Redis service above defines the image that the service is based on and its port mappings. In addition, it defines the command which will be run when Docker builds the Redis image ( command ). The command requires the Redis password ( ${REDIS_PASSWORD} ), which is obtained from the .env file of our Laravel application.

Next, we need to configure a PHP service for our application to run. Add the following lines to the end of the services section in docker-compose.yaml .

The PHP service is a little different to the others. Lets go over some of its key concepts:

Now, create a file named Dockerfile in a new directory docker/php . Note, this file does not have a file extension. Add the configuration below to the file.

This file builds a custom image for the PHP container. The image will be based on the 8.1.24-apache-bookworm tag of the official Docker Hub PHP image. It only makes a few additions, those being adding the PDO MySQL , BC Math , and Redis extensions for PHP.

Then, in the docker/php directory, create a new file named post-start.sh , and add the following code to it.

This is a small shell script that overrides the PHP image's default CMD instruction . The reason for doing this is to ensure that the database migrations are run during startup, in addition to starting Apache. That way, the application's ready to use, without requiring any manual intervention.

The script starts Apache and puts it in the background. Then, it uses Laravel's Artisan Console to run the database migrations. After that, updates the ownership and permissions of the storage directory, so that Laravel's log file can be written to by the web server user ( www-data ). Finally, it brings Apache back into the foreground, listening for requests.

Database migrations can be destructive. So it’s not, always, smart to run them in production. However, it seemed acceptable for the purposes of a simplistic example.

Next, create a file named Dockerfile in a new docker/ node directory, and add the code below to it.

This file builds a custom image for the node container. The image will be based on the 14-alpine tag of the official Docker Hub Nodejs image.

We also need Node.js to handle JavaScript related tasks in our Laravel application. Let's define a service for it. Add the following to the end of the definition in docker-compose.yml , after the php service:

Create a development Docker Compose configuration file

Now, create a new file in the project's top-level directory named docker-compose.dev.yml . This file has additional directives that are only applicable when deploying the application locally, in development. In it, add the configuration below.

The changes in this configuration file map ports in the database (3306), redis (6739), and php (8080) containers to ports on the host (the local development machine). In the case of the database and redis ports, this is so that, if required, we can use clients to interact with them, such as MySQL's command line client.

Start the Docker containers

First up, run the command below.

This symlinks the development configuration file to Docker Compose's second configuration file, docker-compose.override.yml . If Docker Compose finds this file, it will merge the configuration directives in the file with those in the default configuration file.

Now, run the command below to serve up the application.

If you need to stop the container configuration, use the following command.

The command spins up all of the services we have configured and prints out information about them in your terminal. Your terminal should look like the image below, after the command is run.

Output from running docker compose build in a terminal

In a separate terminal tab or window, run docker-compose ps command to see all the running services. Your terminal should look similar to the image below.

Output of running docker compose ps in the terminal

Implement authentication in our application

At this point, our services are running. To ensure that everything works, we need to interact with our database. Let's implement authentication using Laravel Breeze as a way of testing that our Docker configuration works completely.

Install Laravel Breeze using the command below.

Next, we need to run the following commands to set up Laravel Breeze.

Test our application locally

Now you can test that the application works. Start it up, again, by running docker compose up --detach . Then, open http://0.0.0.0:8000/ in your browser. In your browser, you should see the application running, similar to the screenshot below.

The default Laravel landing page

Let’s create a new user to see that our authentication works. Head to the /register route by clicking on the Register link and create a new user, like so.

Registering a new user with Laravel, when Laravel Breeze is integrated into it.

After creating the user, you should be redirected to the application dashboard like so.

The post-registration page, when a new user has successfully registered with Laravel, when integrated with Laravel Breeze.

Now, we are sure our Laravel application works when powered by Docker Compose.

If you'd like to dive deeper into Docker Compose and learn loads more, such as how to debug Docker Compose configurations, download Deploy with Docker Compose . It's free.

Deploy the Laravel application to production with Docker Compose

Prepare the application for deployment.

Good job, if you’ve gotten to this point. Now, let's dive a little deeper by deploying our application to a cloud host service. For the purpose of this tutorial, we will deploy to DigitalOcean.However, the steps are basically the same for most service providers, as long as you have SSH access.

Let's get started by creating a Digital Ocean Droplet . However, before we proceed, update your APP_ENV value in .env from development to production like so.

Create a production Docker Compose configuration file

Now, create a new file in the project's top-level directory named docker-compose.prod.yml . This file has additional directives that are only applicable when deploying the application to production. In it, add the configuration below.

There's very little going on in this configuration. It just maps port 80 in the service to port 80 on the host. That way, the application can be accessed on the standard HTTP port, when deployed.

Set up a new DigitalOcean droplet

Creating a DigitalOcean Docker Droplet is very straightforward, requiring just a few clicks. First, open the Docker app in the DigitalOcean Marketplace. Then, click Create Docker Droplet . From there:

  • Choose the region nearest to you, which should also set the datacenter
  • Leave the image, size, and cpu options set to their defaults
  • Leave the authentication method set to SSH Key and select the applicable SSH key to use to access the droplet
  • Finally, click Create Droplet

After about a few minutes, the new droplet should be ready to use.

Next, we need to ssh into our droplet using its IP address.

A project&#x27;s details within the DigitalOcean dashboard.

To ssh into the server as the root user, replace <<Your Droplet's IP-Address>> in the command below, with the IP address of your droplet, and run it.

Next, let's create a non-root user who can deploy the application , using the commands below.

This command prompts you to create a password for the user. After creating the password, skip through all the other prompts until the user is created.

Lastly, so that the deployment user can login to the droplet, in a new terminal session, create an SSH public key for the deployment user, then copy it to the deployment user's .ssh directory, by running the command below (after replacing the placeholder).

Then, in your original terminal session, set the deployment user as the owner of the public key that you just uploaded for them, by running the command below.

Copy the project files to the droplet

With that done, log in as the deployment user and create a new directory, named laravel_and_docker , in their home directory, by running the command below. This is where our application will be deployed.

Now, we need to copy the files from our local machine to the droplet. There is more than one way of doing this, which you'll see in future tutorials. For the purpose of this tutorial, we will make use of the rsync command, which has a very simple syntax, rsync (options) (location project directory) (server IP address) .

In a third terminal session, run the command below to copy the project files from our local machine to our server.

Deploy the application to production

Now, you're ready to serve up your Laravel project. In the terminal session where you are logged in to the droplet as the deployment user, change into the project directory, symlink the production configuration file to Docker Compose override file, and start the application by running the commands below.

This command would build and serve our Docker containers and we can launch our project using the IP address.

At this point you should be able to view your project on the browser, as you can see in the screenshot below.

The default Laravel landing page

Now, your application should be accessible and function exactly the same way as what we have locally. Lets verify this by creating a new user account and login in with it.

Registering a new user with Laravel, when Laravel Breeze is integrated into it.

That's been a deep dive into Laravel Development with Docker

In this tutorial, we've explored the powerful combination of Laravel development with Docker, enabling you to build, test, and deploy web applications with ease. By creating Docker images for PHP, MySQL, Redis, and Node.js, you've gained the ability to maintain a consistent and reproducible development environment.

You can find the code on GitHub , if you got stuck at any point during the tutorial.

Moses Anumadu is a software developer and online educator who loves to write clean, maintainable code. I create technical contents for technical audiences. You can find me at Laraveldev.pro .

"oakland1" (in the tutorial's main image) by -tarat- is licensed under CC BY-NC-ND 2.0 .

assign ip docker container

Related Posts

Implement CRUD Operations in CakePHP

This tutorial will teach you the essentials of implementing CRUD operations in CakePHP. It illustrates how users can create, read, update, and delete records, thus providing a guide to managing data in your application in CakePHP.

assign ip docker container

In this tutorial, you will learn how to export data from a MySQL database to a CSV file with the CakePHP framework.

assign ip docker container

In this tutorial, you will learn how you can use the Mercure protocol in your Symfony applications to broadcast updates to the frontend.

assign ip docker container

In this tutorial, you will learn how to upload files in CakePHP

How to Store Files on Google Cloud Storage Using PHP

In this tutorial, you're going to learn how to store files using Google Cloud Storage and PHP's Flysystem package.

How to Create a Mock Twilio Lookup API

In this short tutorial, you will learn how to mock Twilio's Lookup API.

Thanks for rating this post!

We are always striving to improve our blog quality, and your feedback is valuable to us. How could this post serve you better?

IMAGES

  1. Docker 101: How To Assign Static IP to Docker Containers

    assign ip docker container

  2. Docker container IP and port discovery with Consul and Registrator

    assign ip docker container

  3. How to Get A Docker Container IP Address

    assign ip docker container

  4. [Solved] How to assign static public IP to docker

    assign ip docker container

  5. Docker set ip address for container

    assign ip docker container

  6. What is a Docker Container for Beginners?

    assign ip docker container

VIDEO

  1. 20. Docker ( In hindi) : Dockerfile ( Expose and create a SSH container using dockerfile )

  2. 04 Docker Networking

  3. SETUP MYSQL DI DOCKER

  4. How to run Multiple Docker Containers in the same Network on Debian 11.3

  5. 2-Docker using

  6. Docker

COMMENTS

  1. How to Assign a Static IP to a Docker Container

    First, you'll need to set up a Docker network, and since we care about the IP address, you'll need to specify a fixed subnet: docker network create --subnet=172.20../16 customnetwork. Then, you can run a container, specifying the network with the --net flag, and specifying the IP with the -ip flag: docker run --net customnetwork --ip 172.20. ...

  2. How can I set a static IP address in a Docker container?

    1. You can start a container with -e WEAVE_CIDR=ip:192.168.1.2/24, and given you have Weave Net running along with proxy environment setup in your shell ( weave launch; eval $ (weave env) ), that container should get the IP address you have specified. - errordeveloper. Jan 18, 2016 at 14:05.

  3. Assign Static IP to Docker Container and Docker-Compose

    The container gets a private 172.19..2 IP address from the subnet created by the network. Most importantly, we can see info about IPAMConfig, which is the IP address management. It will be relevant when we'll statically assign the IP. Now, we can inspect the network: docker inspect network project_network.

  4. Assigning IP address to docker containers?

    5. Docker evolved a lot during last so as for Docker 0.6.5: Containers have their own ip addresses now. You can check the ip address of a container using docker inspect command or if you are interested into extracting it you can use: docker inspect container_name | grep IPAddress | cut -d '"' -f 4. Share.

  5. Networking overview

    The Docker daemon performs dynamic subnetting and IP address allocation for containers. Each network also has a default subnet mask and gateway. When a container starts, it can only attach to a single network, using the --network flag. You can connect a running container to additional networks using the docker network connect command.

  6. How to Provide the Static IP to a Docker Container?

    Solution: Step 1: Configure the Docker in the Server. Installation of Docker. Pulling the Latest Nginx Image. Show the Images. Step 2: Create a Network with Subnet (CIDR). Creating Network. List the Network. Step 3: Deploy the Container this Network with your Custom Static IP.

  7. docker network connect

    To verify the container is connected, use the docker network inspect command. Use docker network disconnect to remove a container from the network.. Once connected in network, containers can communicate using only another container's IP address or name.

  8. How to Get A Docker Container IP Address

    Docker Container IP Address. By default, the container is assigned an IP address for every Docker network it connects to. And each network is created with a default subnet mask, using it as a pool later on to give away the IP addresses. Usually Docker uses the default 172.17. 0.0/16 subnet for container networking.

  9. Is it possible to assign the host's IP address to a docker container

    Since domain is getting resolved to your host, you only need to expose dockerized web server's port 80 as host's port. Docker supports this by the means of port publishing which is enabled using the -p option of docker run. docker run -it --rm -p 80:80 nginx. Presumably you want to run the DB, web server and PHP in separate containers.

  10. Docker 101: How To Assign Static IP to Docker Containers

    One of the issues that beginners will encounter is IP assignment to docker containers. By default, IP address are assigned as "first come, first serve". Mean...

  11. How to assign static public IP to a docker container

    Then start the first container: docker run -p 192.168.10.10:80:80 mywebserver. And finally start the second container: docker run -p 192.168.10.20:80:80 mywebserver. In the above commands, the -p option is used to bind the port mapping to a particular ip address. Now you have two containers offering a service on the same port (port 80) but on ...

  12. Assign static IP to a Docker container

    Assign static IP to a Docker container. Oct 24, 2021 · 1 min read · Post a comment. There are two types of static IPs, public and private IP addresses. We all know the public IP Docker mapping by now, using Nginx and port mapping. Today we are going to see how can we assign a private IP address to a Docker container.

  13. Assign a Static IP to a Docker Container

    When a Docker container starts up, it gets a dynamic IP address by default. In this article, we will show you how to assign a static IP address to a specific Docker container. Create a new Docker network: $ docker network create --subnet=172.11../16 mycustomnetwork. You can run a docker container in this network with a specific (static) IP ...

  14. How to Run Multiple Docker Containers on Different IP Addresses

    So, for example, you could have two NGINX containers on different IPs, like so (keep in mind, Docker needs separate container names): docker run -it -d 123.0.0.1:80:80 --name web nginx. docker run -it -d 123.0.0.2:80:80 --name web2 nginx. If you're using Docker Compose, the configuration is similar. In the ports section for the service, you can ...

  15. Router assign ip to docker container

    1 Answer. Launching the container with --net=bridge you are connecting the container with default Docker bridge (network 172.17../16), which is the default behavior for network configuration. There is an open issue in Docker to implement this feature in an easy way. But now you will have to perform some actions manually to get what you want:

  16. How can I assign an IP address to a docker container different from the

    Objective: Assign fixed IP address to Docker container (Unifi Controller instance).. History: I fetched the unifi controller image from Docker Hub to my Synology Docker host. The container of the unifi controller runs properly if I attach it to the network of the host (not the default bridge). That blocks though multiple ports I need for other services (in the future).

  17. Advanced container settings

    Note that you cannot assign a static IP address to a container that is in Docker's default bridge network. This is a Docker limitation rather than Portainer. ... The container will also always start on Docker startup, regardless of the current state of the container. On failure: Restart only if the container exits with a non-zero exit status.

  18. Assigning multiple IP Addresses to Docker Container

    Sorted by: 3. You can configure your docker container to use multiple IP addresses, at least in two ways: Add additional IP addresses inside the container manually: container # ip address add 172.17.1.4/32 dev eth0 container # ip address add 172.17.1.5/32 dev eth0 ... Note: These addresses probably need to belong to the container's subnet, not ...

  19. Assign Public IP Address to Docker Container without Port Binding

    Docker. Assign Public IP Address to Docker Container without Port Binding. 2022-07-17. ... Above command runs nginx container with ip '88.99.102.115' attached to this container, you can verify by hitting '88.99.102.115' where you will be welcomed with nginx page.

  20. How to Assign Static IP Addresses to Docker Compose Containers

    Now you can start containers using the docker-compose up command. Add the -d flag if you need to start containers in the detached (background) mode. When we start Docker containers with Docker Compose, all the service containers in it will get dynamically assigned IP addresses. For example, if you run the containers in the below docker-compose.

  21. Provide static IP to docker containers via docker-compose

    Static IP's will decrease flexibility, including the ability to do a rolling update of your application, not work in swarm mode, and make the container's configuration harder to copy between environments or similar containers. For the linked issue, you just need to listen on 0.0.0.0 inside the container. - BMitch.

  22. Deep Dive into Laravel Development with Docker

    Then, open .env in your preferred text editor or IDE and make the following three changes:. Set DB_HOST to database.This needs to match the hostname of the container containing the database. Set DB_USERNAME to laravel.It's best to use an account other than root to connect to a database.; Set a value for DB_PASSWORD; Laravel applications require multiple services to function.

  23. docker

    Assign static IP to Docker container. 349 How to mount host volumes into docker containers in Dockerfile during build. Load 6 more related questions Show fewer related questions Sorted by: Reset to default Know someone who can answer? Share a link to this ...