简体   繁体   中英

Replace ip:port to another ip:port using sed

I have nginx config file, where i have ip adress of my container. If i recreate container it will have the new ip, so i want to replace it.

I have .sh script:

#!/bin/bash
ip_new=$(sudo docker exec -ti pqf_ui_dev hostname -I) #to assign  container ip to this variable
sudo sed  "s~proxy_pass http[:]//[^ ][:]80*~proxy_pass http://$ip_new:80~"  -i /etc/nginx/sites- 
enabled/docker-pqf

so for example if my old ip:port was 172.17.0.1:80 and the new one is 172.17.0.2:80, my sed replace it like:

proxy_pass http://172.17.0.4 ^M:80

How i can change my script to replace ip without this ^M ?

Use:

ip_new=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' pqf_ui_dev)

Instead of:

ip_new=$(sudo docker exec -ti pqf_ui_dev hostname -I)

And maybe you may like this sed:

sudo sed -E 's~(proxy_pass https?://)[^ :;]+(:?\\d*)~\\1'$ip_new'\\2~' -i /etc/nginx/sites- enabled/docker-pqf

It is not perfect, but way more universal and without repeating searchtext like proto, host, port.

If I were doing this I would run the nginx proxy in a container also and proxy_pass to the container name rather than a dynamic IP that will keep changing.

eg if using a compose file

version: '3.7'
services:
  proxy:
    image: nginx
    # Docker config required for nginx
  backend: 
    # Config for your backend service
    ports:
     - "80:80"

Then in your nginx conf file you can refer to the backend service as http://backend:80 and docker DNS will resolve the IP address for you complete with load balancing if you have multiple instances running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM