I created an API using node.js
I converted it to an image by running the command docker build -t droneapi:1.0
using this Dockerfile.
FROM node:19-alpine
ENV MONGO_DB_USERNAME = admin \
MONGO_DB_PWD=password
RUN mkdir -p /home/droneAPI
COPY . /Users/styles/Programming/DroneAPI2
CMD ["node", "/Users/styles/Programming/DroneAPI2/Drones/server.js"]
I ran docker run droneapi:1.0 to create a container to talk to my mongodb container but I received the error: getaddrinfo ENOTFOUND mongodb
I’m using mongoose to try and communicate with the db
onst connectDB = async () => {
try{
const conn = await mongoose.connect("mongodb://admin:password#mongodb:27017", {dbName: 'drobedb'})
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline)
}catch (error){
console.log(`Error: ${error.message}`.red.underline.bold)
process.exit(1)
}
}
I have tried to replace the 'mongodb' in the connection string with localhost and I receive Error: connect ECONNREFUSED 127.0.0.1:27017
Here is my mongo.yaml file
version: '3'
services:
mongodb:
image: mongo
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
mongo-express:
image: mongo-express
ports:
- 8081:8081
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
- ME_CONFIG_MONGODB_ADMINPASSWORD=password
- ME_CONFIG_MONGODB_SERVER=mongodb
I'm new to docker so please any assistance will be appreciated
When we start a container stack through a compose-file, a network for this compose stack is created for us, and all containers are attached to this network. When we start a container through docker run ..., it is attached to the default network. Containers in different networks cannot communicate with each other. My recommendation would be to add the dronapi-container to the compose file:
version: '3'
services:
...
drone-api:
bulid:
context: .
dockerfile: path/to/Dockerfile
...
depends_on:
- mongodb # to start this container after mongodb has been started
If we want to start the stack, we can run docker compose up -d. Notice that if the image was built before, it will not be automatically rebuilt. To rebuild the image, we can run docker compose up --build -d.
As an aside: I would recommend following the 12 factors for cloud-native applications (12factors.net). In particular, I would recommend to externalize the database configuration (12factors.net).
Related
Code
https://github.com/thiskevinwang/rust-redis-docker/tree/for-stackoverflow
Context:
Written in Rust
Cargo.toml:
[dependencies]
redis = "0.16.0"
hyper = "0.13"
Local development ✅
Things that work:
running a redis docker container bitnami/redis, published with -p 6379:6379
redis-cli can connect to this docker container successfully
browser can hit the rust code at localhost:3000
GET / displays some text ✅
GET /redis increments a counter in redis, and displays it ✅
Running rust-code in docker ❌
The rust docker container fails to connect to the redis docker container
running the same redis docker container bitnami/redis,
browser can hit the rust-container at localhost:3000
GET / displays some text, as before ✅
GET /redis causes rust code to panic ❌
Connection refused (os error 111)
I'm not sure if this is a problem with me incorrectly handling "docker networking" or if I'm using the redis crate incorrectly (although documentation is pretty sparse).
You have this in docker-compose.yaml:
services:
hyper:
build: .
ports:
- "3000:3000"
expose:
- "3000"
links:
- redis # links this container to "redis" container
redis:
image: "bitnami/redis:latest"
ports:
- "6379:6379"
expose:
- "6379"
From the Docker Compose docs on links:
Containers for the linked service are reachable at a hostname identical to the alias, or the service name if no alias was specified.
So therefore the error is on line 70 in main.rs:
let client = redis::Client::open("redis://127.0.0.1:6379")?;
That doesn't work since the redis instance is not running in the same container as your Rust code. You have to connect to it through the link established in your docker compose file, which in this case would be:
let client = redis::Client::open("redis://redis:6379")?;
Once you make this fix fetching GET localhost:3000/redis returns successfully.
i am using akka http server in my app and mongodb as a backed database, akka http uses standard input to keep running the server,
here is how i am binding it
val host = "0.0.0.0"
val port = 8080
val bindingFuture = Http().bindAndHandle(MainRouter.routes, host, port)
log.info("Server online ")
StdIn.readLine()
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
i need to dockerize my app docker closes the standard input by default when it starts the container, to keep it running we need to provide -i option with the container like this
docker run -p 8080:8080 -i imagename:tag
now the problem is i need to use docker-compose to start my app with mongo
here is my docker-compose.yml
version: '3.3'
services:
mongodb:
image: mongo:4.2.1
container_name: docker-mongo
ports:
- "27017:27017"
akkahttpservice:
image: app:0.0.1
container_name: docker-app
ports:
- "8080:8080"
depends_on:
- mongodb
how can i provide the -i option with docker-app container
Note after doing docker-compose up
docker exec -it containerid sh
did not worked for me
Any help would be appreciated
I have created a docker-compose file it has two services with Go and Mysql. It creates container for go and mysql. Now i am running code which try to connect to mysql database which is running as a docker container. but i get error.
docker-compose.yml
version: "2"
services:
app:
container_name: golang
restart: always
build: .
ports:
- "49160:8800"
links:
- "mysql"
depends_on:
- "mysql"
mysql:
image: mysql
container_name: mysql
volumes:
- dbdata:/var/lib/mysql
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=testDB
- MYSQL_USER=root
- MYSQL_PASSWORD=root
ports:
- "3307:3306"
volumes:
dbdata:
Error while connecting to mysql database
golang | 2019/02/28 11:33:05 dial tcp 127.0.0.1:3306: connect: connection refused
golang | 2019/02/28 11:33:05 http: panic serving 172.24.0.1:49066: dial tcp 127.0.0.1:3306: connect: connection refused
golang | goroutine 19 [running]:
Connection with MySql Database
func DB() *gorm.DB {
db, err := gorm.Open("mysql", "root:root#tcp(mysql:3306)/testDB?charset=utf8&parseTime=True&loc=Local")
if err != nil {
log.Panic(err)
}
log.Println("Connection Established")
return db
}
EDIT:Updated docker file
FROM golang:latest
RUN go get -u github.com/gorilla/mux
RUN go get -u github.com/jinzhu/gorm
RUN go get -u github.com/go-sql-driver/mysql
COPY ./wait-for-it.sh .
RUN chmod +x /wait-for-it.sh
WORKDIR /go/src/app
ADD . src
EXPOSE 8800
CMD ["go", "run", "src/main.go"]
I am using gorm package which lets me connet to the database
depends_on is not a verification that MySQL is actually ready to receive connections. It will start the second container once the database container is running regardless it was ready for connections or not which could lead to such an issue with your application as it expects the database to be ready which might not be true.
Quoted from the documentation:
depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started.
There are many tools/scripts that can be used to solve this issue like wait-for which sh compatible in case your image based on Alpine for example (You can use wait-for-it if you have bash in your image)
All you have to do is to add the script to your image through Dockerfile then use this command in docker-compose.yml for the service that you want to make it wait for the database.
What comes after -- is the command that you would normally use to start your application
version: "2"
services:
app:
container_name: golang
...
command: ["./wait-for", "mysql:3306", "--", "go", "run", "myapplication"]
links:
- "mysql"
depends_on:
- "mysql"
mysql:
image: mysql
...
I have removed some parts from the docker-compose for easier readability.
Modify this part go run myapplication with the CMD of your golang image.
See Controlling startup order for more on this problem and strategies for solving it.
Another issue that will rise after you solve the connection issue will be as the following:
Setting MYSQL_USER with root value will cause a failure in MySQL with this error message:
ERROR 1396 (HY000) at line 1: Operation CREATE USER failed for 'root'#'%'
This is because this user already exist in the database and it tries to create another. if you need to use the root user itself you can use only this variable MYSQL_ROOT_PASSWORD or change the value of MYSQL_USER so you can securely use it in your application instead of the root user.
Update: In case you are getting not found and the path was correct, you might need to write the command as below:
command: sh -c "./wait-for mysql:3306 -- go run myapplication"
First, if you are using latest version of docker compose you don't need the link argument in you app service. I quote the docker compose documentation Warning: The --link flag is a legacy feature of Docker. It may eventually be removed. Unless you absolutely need to continue using it, https://docs.docker.com/compose/compose-file/#links
I think the solution is to use the networks argument. This create a docker network and add each service to it.
Try this
version: "2"
services:
app:
container_name: golang
restart: always
build: .
ports:
- "49160:8800"
networks:
- my_network
depends_on:
- "mysql"
mysql:
image: mysql
container_name: mysql
volumes:
- dbdata:/var/lib/mysql
restart: always
networks:
- my_network
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=testDB
- MYSQL_USER=root
- MYSQL_PASSWORD=root
ports:
- "3307:3306"
volumes:
dbdata:
networks:
my_network:
driver: bridge
By the way, if you only connect to Mysql from your app service you don't need to expose the mysql port. If the containers runs in the same network they can reach all ports inside this network.
If my example doesn't works try this
run the docker compose and next go into the app container using
docker container exec -it CONTAINER_NAME bash
Install ping in order to test connection and then run ping mysql.
I have a simple python service that sends a single command to a running bitcoin server. When I run a local bitcoin daemon everything works fine. However, when I try to run this using Docker I cannot connect this service to a bitcoin server in another docker image, like in this docker-compose:
version: '3'
services:
my_service:
build: .
volumes:
- .:/app
depends_on:
- bitcoind
links:
- bitcoind
working_dir: /app
bitcoind:
image: ruimarinho/bitcoin-core:0.15.0.1-alpine
command:
-printtoconsole
-regtest=1
-rest
-rpcallowip=10.211.0.0/16
-rpcallowip=172.17.0.0/16
-rpcallowip=192.168.0.0/16
-rpcpassword=bar
-rpcport=18333
-rpcuser=foo
-server
ports:
- 18333:18333
volumes:
bitcoin_data:
I keep getting the following error:
ConnectionError: HTTPConnectionPool(host='bitcoind', port=18333): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7faded979310>: Failed to establish a new connection: [Errno -2] Name or service not known',))
Any ideas?
You must open the container port 18333. With the docker compose, you can use the command 'expose' to do it.
I am trying to use Docker Compose (with Docker Machine on Windows) to launch a group of Docker containers.
My docker-compose.yml:
version: '2'
services:
postgres:
build: ./postgres
environment:
- POSTGRES_PASSWORD=mysecretpassword
frontend:
build: ./frontend
ports:
- "4567:4567"
depends_on:
- postgres
backend:
build: ./backend
ports:
- "5000:5000"
depends_on:
- postgres
docker-compose build runs successfully. When I run docker-compose start I get the following output:
Starting postgres ... done
Starting frontend ... done
Starting backend ... done
ERROR: No containers to start
I did confirm that the docker containers are not running. How do I get my containers to start?
The issue here is that you haven't actually created the containers. You will have to create these containers before running them. You could use the docker-compose up instead, that will create the containers and then start them.
Or you could run docker-compose create to create the containers and then run the docker-compose start to start them.
The reason why you saw the error is that docker-compose start and docker-compose restart assume that the containers already exist.
If you want to build and start containers, use
docker-compose up
If you only want to build the containers, use
docker-compose up --no-start
Afterwards, docker-compose {start,restart,stop} should work as expected.
There used to be a docker-compose create command, but it is now deprecated in favor of docker-compose up --no-start.